尝试使用Python 3读取json文件并写入csv文件时获取JSONDecodeError吗?
我已经编写了一个脚本来从mongodb中获取数据,并将得到的结果转换为扁平化的json格式,并将其存储到json文件-data_flatten_json.json中。但是当我尝试读取相同的json文件并将其转换为csv文件-data.csv时。面临问题
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包含数据
{
"_id": {
"$oid": "5cdd5ea359af317620aae420"
},
"email": "abc@domain.com",
"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": "xyz@domain.com",
"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
}
}
]
}
}
我期待一个csv输出。
面对错误:
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)
答案 0 :(得分:0)
输入的JSON无效,它包含两个 JSON对象。可以使用JSON数组包装它们。或删除其中一个对象。
这是不可能的:
]
}
}{
"_id": {
"$oid": "5cde5bc559af310ea00c42b7"
}