尝试在添加根节点时尽可能简单地将CSV文件转换为JSON文件。出于某种原因,JSON文件至少省略了CSV文件末尾的最后一行(在某些情况下多达4行)。这里发生了什么?
示例CSV
name, id, tag
John, 12345, father
Mary, 33456, sister
Beth, 56789, daughter
所需的JSON
{"node": "", "children": [
{"name": "John", "id": 12345, "tag": "father"},
{"name": "Mary", "id": 33456, "tag": "sister"},
{"name": "Beth", "id": 56789, "tag": "daughter"}
]}
我得到了什么:
{"node": "", "children": [
{"name": "John", "id": 12345, "tag": "father"},
{"name": "Mary", "id": 33456, "tag": "sister"},
]}
我的代码:
csvfile = open('file.csv', 'r')
jsonfile = open('file.json', 'w')
reader = csv.DictReader(csvfile)
jsonfile.write('{"node": "", "children": [')
for row in reader:
json.dump(row, jsonfile)
#jsonfile.write(',\n')
jsonfile.write('] }')
P.S。我知道我在JSON文件的最后一行添加了一个逗号 - 我也想知道如何在最后一行之后添加逗号,但这不太重要。
答案 0 :(得分:2)
您不需要手动构建JSON字符串。创建一个Python数据结构,然后通过json.dump()
将其转储到json文件中:
import json
reader = csv.DictReader(csvfile)
data = {"node": "", "children": list(reader)}
with open('file.json', 'w') as jsonfile:
json.dump(data, jsonfile)