Python CSV 到 JSON 引用嵌套对象

Python CSV to JSON is quoting nested objects

提问人:rabowlen 提问时间:6/10/2020 更新时间:6/10/2020 访问量:116

问:

我正在使用以下内容将 CSV 文件转换为 JSON。问题是,任何嵌套的对象都会被引用。如何解决此问题,以便将输出传递给终结点?

def csvToJson(tokenHeader):
data = []
with open('CSV/quiz-questions.csv') as questionFile:
    csv.field_size_limit(sys.maxsize)
    csvReader = csv.DictReader(questionFile)
    for row in csvReader:
        row = {key: (None if value == "" else value) for key, value in row.items()}
        row = {key: ([] if value == "[]" else value) for key, value in row.items()}
        data.append(json.dumps(row, indent=4, ensure_ascii=False))

输出片段:

"question": "{'guid': ...
Python JSON CSV 行情

评论

0赞 bherbruck 6/10/2020
CSV文件的格式是什么?您的 csv 平面文件是否模拟嵌套数据?
0赞 rabowlen 6/10/2020
我刚刚从端点写入了 csv:file = open('CSV/quiz-questions.csv', 'w') csvwriter = csv.writer(file)
0赞 bherbruck 6/10/2020
你为什么要使用?json.dumps()

答:

0赞 bherbruck 6/10/2020 #1

您可以使用此函数将 csv 读入具有 column: 值结构的字典列表中:

import csv

def open_csv(path):
    '''return a list of dictionaries
    '''
    with open(path, 'r') as file:
        reader = csv.DictReader(file)
        # simple way to do the replacements, but do you really need to do this?
        return [{k: [] if v == '[]' else v or None
                 for k, v in dict(row).items()}
                for row in reader]

data = open_csv('test.txt')

# output to json because it looks better, null is None
import json
print(json.dumps(data, indent=4))

测试 .csv

name,age,hobby,countries
foo,31,,"['123', 'abc']"
bar,60,python programming,[]

输出:

[
    {
        "name": "foo",
        "age": "31",
        "hobby": null,
        "countries": "['123', 'abc']"
    },
    {
        "name": "bar",
        "age": "60",
        "hobby": "python programming",
        "countries": []
    }
]
0赞 rabowlen 6/10/2020 #2

我通过处理写作方面的事情解决了这个问题。当我将我的问题传递到 CSV 中时,我正在使用我的嵌套对象创建一个字典。这在从 CSV 读取时令人头疼。所以现在我用这行来修复我的嵌套对象:

question = {key: (json.dumps(value) if key in ['question', etc. etc.] else value) for key, value in question.items()}