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

2024-04-20 09:56:02 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码,非常简单的东西。。。

import csv
import json

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

fieldnames = ("FirstName","LastName","IDNumber","Message")
reader = csv.DictReader( csvfile, fieldnames)
out = json.dumps( [ row for row in reader ] )
jsonfile.write(out)

声明一些字段名,读取器使用CSV读取文件,文件名将文件转储为JSON格式。问题是。。。

CSV文件中的每个记录都在不同的行上。我希望JSON输出是相同的方式。问题是它把一切都抛在一条巨大的长线上。

我试过使用类似for line in csvfile:的方法,然后使用reader = csv.DictReader( line, fieldnames)运行下面的代码,该代码循环遍历每一行,但它在一行上执行整个文件,然后在另一行上循环遍历整个文件。。。一直持续到排不完为止。

有什么改正的建议吗?

编辑:为了澄清,目前我有:(第1行的每个记录)

[{"FirstName":"John","LastName":"Doe","IDNumber":"123","Message":"None"},{"FirstName":"George","LastName":"Washington","IDNumber":"001","Message":"Something"}]

我要找的是:(两行两张唱片)

{"FirstName":"John","LastName":"Doe","IDNumber":"123","Message":"None"}
{"FirstName":"George","LastName":"Washington","IDNumber":"001","Message":"Something"}

不是每个字段缩进/在单独的行上,而是每个记录在自己的行上。

一些样本输入。

"John","Doe","001","Message1"
"George","Washington","002","Message2"

Tags: 文件csvcsvfile代码jsonmessage记录firstname
3条回答

您可以使用Pandas DataFrame来实现这一点,例如:

import pandas as pd
csv_file = pd.DataFrame(pd.read_csv("path/to/file.csv", sep = ",", header = 0, index_col = False))
csv_file.to_json("/path/to/new/file.json", orient = "records", date_format = "epoch", double_precision = 10, force_ascii = True, date_unit = "ms", default_handler = None)

我接受了@SingleNegationElimination的响应,并将其简化为三行,可以在管道中使用:

import csv
import json
import sys

for row in csv.DictReader(sys.stdin):
    json.dump(row, sys.stdout)
    sys.stdout.write('\n')

所需输出的问题是它不是有效的json文档;它是json文档的

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

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

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')

相关问题 更多 >