How to generate JSON from the csv file in Python?

Viewed 1323

I am trying to construct a Json structure from the csv file. This below code gives me the error stating :- AttributeError: 'tuple' object has no attribute 'to_json' . I am new to python world and would like to ask for your help on this.

CSV Data Look like this:

enter image description here

I want output to be like below

[
    {"Variable": "Latitude",
    "Min": "78",
    "Q1": "89"} ,

    {"Variable": "Longitude",
    "Min": "78",
    "Q1": "89"},
    {"Variable": "Zip",
    "Min": "78",
    "Q1": "89"}
]

import pandas    
res_data = pd.read_csv("C\\Documents\\abc.csv", 'r')
abc=res_data.to_json(orient='records')
print(abc)
3 Answers
import json
import pandas as pd    
df = pd.read_csv("path_of_csv")
js = df.to_json(orient="records")
json.loads(js)

Output:

[{'variable': 'Latitude', 'min': 26.84505, 'Q1': 31.19725},
 {'variable': 'Longtitude', 'min': -122.315, 'Q1': -116.558},
 {'variable': 'Zip', 'min': 20910.0, 'Q1': 32788.5}]

Something like

import csv
import json

csvfile = open('file.csv', 'r')
jsonfile = open('file.json', 'w')

fieldnames = ("variable", "min", "Q1")
reader = csv.DictReader( csvfile, fieldnames)
for row in reader:
    json.dump(row, jsonfile)
    jsonfile.write('\n')

You can try simply using csv module.

import csv
import json

output_dict = []
with open('abc.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        output_dict.append(row)

print json.dumps(output_dict)

output_dict will contain list of dict of include all rows. json.dumps will convert python dict to json.

and output will be:

[{'variable': 'Latitude', 'min': 26.84505, 'Q1': 31.19725},
 {'variable': 'Longtitude', 'min': -122.315, 'Q1': -116.558},
 {'variable': 'Zip', 'min': 20910.0, 'Q1': 32788.5}]

More details abou csv.DictReader : enter link description here

Related