4

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)
1
  • 1
    What is res_df here? Commented Nov 16, 2018 at 8:47

3 Answers 3

3
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}]
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. Simple and best
0

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')

1 Comment

It works but not generating the proper json structure. There should be comma separated for each row and the whole json should be enclosed in []
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.