简体   繁体   中英

Empty cells become “” when converting CSV to JSON - Python

Currently I am using the code below to convert a CSV into JSON. The problem is, that the return puts empty strings for values that are empty in the CSV. I need these to be null in order for api calls to work.

How can I get null for values that are blank in the CSV?

def csvToJson(tokenHeader):
    data = []
    with open('CSV/quiz-questions.csv') as questionFile:
        csv.field_size_limit(sys.maxsize)
        csvReader = csv.DictReader(questionFile, quoting=csv.QUOTE_MINIMAL)
        for row in csvReader:
            data.append(row)

    with open('JSON/questions.json', 'w+') as jsonFile:
        jsonFile.write(json.dumps(data, indent=4))

Convert all the empty strings to None before appending to the list.

for row in csvReader:
    row = {key: (None if value == "" else value) for key, value in row.items()}
    data.append(row)

Python None is translated to JSON null .

BTW, you can use json.dump(jsonFile, data, indent=4) rather than calling jsonFile.write() and json.dumps() separately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM