去年我有一个Python初学者课程。现在我正试图获得一个csv到json转换器。我搜索了一段时间,并修改了一些我找到的代码,直到输出看起来类似于我想要的。我正在使用Python 3.4.2。Python:csv到json转换器的值到密钥对
@kvorobiev这是我的CSV的摘录,但它会做的案件。第一次转换将工作。第二次后,你会看到标题的顺序会在json文件中改变。
CSV文件看起来像这样
Document;Item;Category
4;10;C
我所得到的输出文件,截至目前(应用从kvorobiev变化后):以
[
{
"Item": "10",
"Category": "C",
"Document": "4"
};
]
JSON字符串我想进入输出文件应该看起来像:
[
{
"Document": "4",
"Item": "10",
"Category": "C"
},
]
你会注意到标题在wron g订单。
下面是代码:
import json
import csv
csvfile = open('file1.csv', 'r')
jsonfile = open('file1.csv'.replace('.csv','.json'), 'w')
jsonfile.write('[' + '\n' + ' ')
fieldnames = csvfile.readline().replace('\n','').split(';')
num_lines = sum(1 for line in open('file.csv')) -1
reader = csv.DictReader(csvfile, fieldnames)
i = 0
for row in reader:
i += 1
json.dump(row, jsonfile, indent=4,sort_keys=False)
if i < num_lines:
jsonfile.write(',')
jsonfile.write('\n')
jsonfile.write(' ' + ']')
print('Done')
感谢您的帮助。
你输出JSON是有效的?你可以检查http://jsonlint.com/? –
谢谢Vivek。我不知道json输出是否有效,但这是我需要进一步处理数据。 – user87290