【发布时间】:2016-01-27 23:17:45
【问题描述】:
尝试在添加根节点的同时尽可能简单地将 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('] }')
附:我知道我要在 JSON 文件的最后一行添加逗号——除了最后一行之外,我也很想知道如何添加逗号,但这并不重要。
【问题讨论】: