Python CSV到JSON引用嵌套对象

问题描述 投票:0回答:2

我正在使用以下内容将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 quotes
2个回答
0
投票

您可以使用此功能将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))

test.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
投票

我通过在书写方面进行处理解决了这个问题。将问题传递到CSV时,我正在使用嵌套对象创建字典。从CSV读取时,这会引起头痛。所以现在我用这一行来修复我的嵌套对象:

question = {key: (json.dumps(value) if key in ['question', etc. etc.] else value) for key, value in question.items()}
© www.soinside.com 2019 - 2024. All rights reserved.