Json to Csv convert using Python

Json to Csv convert using Python


Hi Friends,

In this video we will learn to convert json data/file array object into csv(excel) file..





sample.json file contains:


{
 "result": [
  {
    "name": "Tharun",
    "age": 23,
    "secretIdentity": "Dan Jukes",
    "marks": 90,
"country" : "India"
  },
  {
    "name": "Vijay",
    "age": 24,
    "secretIdentity": "Jane Wilson",
    "marks": 70,
"country": "USA"
  },
  {
    "name": "John",
    "age": 29,
    "secretIdentity": "DEN",
    "marks": 65,
"country" : "AUS"
  }
]
}


and jsontocsv_converter.py contains

#Author https://ittechtarun.blogspot.com/
import json
import csv
with open("./my_json.json") as file:
    data = json.load(file)

fname = "output.csv"

with open(fname, "w") as file:
    csv_file = csv.writer(file,lineterminator='\n')
    csv_file.writerow(["Name","Age","Marks","Country"])
    for item in data["result"]:
        csv_file.writerow([item['name'],item['age'],item['marks'],item['country']])








If you want to load data from weburl you can use this code

How to load json data from web url ?

Here Im importing some patients data from weburl into csv file
you can see the patients infromation in this url : https://api.covid19india.org/raw_data1.json
you can replace it with your json data weburl

#Author IT-Tech-Tharun
#Author https://ittechtarun.blogspot.com/
import json
import csv
import urllib.request
with urllib.request.urlopen("https://api.covid19india.org/raw_data1.json") as url:
    data = json.loads(url.read().decode())

fname = "output.csv"

with open(fname, "w") as file:
    csv_file = csv.writer(file,lineterminator='\n')
    csv_file.writerow(["gender","patientnumber","currentstatus","statepatientnumber"])
    for item in data["raw_data"]:
        csv_file.writerow([item['gender'],item['patientnumber'],item['currentstatus'],item['statepatientnumber']])


In the code I specifically mentioned pull 4 fields from weburl to excel sheet.









Post a Comment

0 Comments