且构网

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

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

更新时间:2023-02-14 11:53:42

所需输出的问题是它不是有效的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('\n')