Getting JSONDecodeError when trying to read a json file and write to a csv file using Python 3?
I'm have written a script to fetch the data from mongodb and the result got is converted to flattened json format, stored it to a json file - data_flatten_json.json. But when I try to read the same json file and convert them to csv file - data.csv. Facing issue
with open('data_flatten_json.json') as json_file:
data = json.load(json_file)
f = open('data.csv')
csv_file = csv.writer(f)
for item in data:
csv_file.writerow(item)
f.close()
data_flatten_json.json contains data
{
"_id": {
"$oid": "5cdd5ea359af317620aae420"
},
"email": "[email protected]",
"user_info": {
"name": "abc",
"city": "Bengaluru",
"age_group": "36 - 40 years",
"marital_status": "Married",
"c_shaving_hurt": "Strongly agree",
"c_shaving_convenience": "Strongly agree",
"c_shaving_skip": "Agree",
"c_shaving_groomed": "Disagree",
"c_shaving_feel": "Strongly agree"
},
"studies": {
"questions": [
{
"_id": {
"$oid": "5cdd3f5a59af317620aae3a6"
},
"image_url": "https://video.svg",
"question_order_number": 1,
"question_type": "text",
"question": "How do you shave or trim your beard?",
"answer_type": "video",
"question_videos": [],
"answers": "",
"updated_at": {
"$date": 1558003546858
},
"created_at": {
"$date": 1558003546858
}
}
]
}
}{
"_id": {
"$oid": "5cde5bc559af310ea00c42b7"
},
"email": "[email protected]",
"user_info": {
"name": "xyz",
"city": "Togo",
"age_group": "18 - 21 years",
"marital_status": "Divorced",
"c_shaving_hurt": "Agree",
"c_shaving_convenience": "Strongly agree",
"c_shaving_skip": "Neither agree not disagree",
"c_shaving_groomed": "Agree",
"c_shaving_feel": "Disagree"
},
"studies": {
"questions": [
{
"_id": {
"$oid": "5cdd3f5a59af317620aae3a6"
},
"image_url": "https://video.svg",
"question_order_number": 1,
"question_type": "text",
"question": "How do you shave or trim your beard?",
"answer_type": "video",
"question_videos": [],
"answers": "",
"updated_at": {
"$date": 1558003546858
},
"created_at": {
"$date": 1558003546858
}
}
]
}
}
I am expecting a csv output.
Facing error:
Traceback (most recent call last):
File "/Users/srinivas/PycharmProjects/FirstProject/TEST1.py", line 66, in <module>
data = json.load(json_file)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 30 column 2 (char 1146)