【问题标题】:Converting CSV to JSON omits last row?将 CSV 转换为 JSON 会省略最后一行?
【发布时间】: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 文件的最后一行添加逗号——除了最后一行之外,我也很想知道如何添加逗号,但这并不重要。

【问题讨论】:

    标签: python json csv


    【解决方案1】:

    您不需要手动构造 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)
    

    【讨论】:

    • 这是更严格的代码——谢谢!——但它似乎并没有解决问题。 csv 文件的最后一行仍然被忽略,或者在某些情况下,用“null”替换某些值(尽管值在 CSV 中显示得很好),然后忽略它后面的行。
    猜你喜欢
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 2015-08-23
    • 2019-08-21
    • 2011-04-27
    相关资源
    最近更新 更多