且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将 CSV 文件转换为多行 JSON?

更新时间:2023-02-14 12:16:04

您想要的输出的问题是它不是有效的 json 文档;这是一个json文档流

The problem with your desired output is that it is not valid json document,; it's a stream of json documents!

没关系,如果它是您需要的,但这意味着对于您想要在输出中的每个文档,您必须调用 json.dumps.

That's okay, if its what you need, but that means that for each document you want in your output, you'll have to call json.dumps.

由于您要分隔文档的换行符未包含在这些文档中,因此您需要自己提供换行符.所以我们只需要将循环从对 json.dump 的调用中拉出来,并为每个写入的文档插入换行符.

Since the newline you want separating your documents is not contained in those documents, you're on the hook for supplying it yourself. So we just need to pull the loop out of the call to json.dump and interpose newlines for each document written.

import csv
import json

csvfile = open('file.csv', 'r')
jsonfile = open('file.json', 'w')

fieldnames = ("FirstName","LastName","IDNumber","Message")
reader = csv.DictReader( csvfile, fieldnames)
for row in reader:
    json.dump(row, jsonfile)
    jsonfile.write('
')