基本Python csv到json脚本会在最终的JSON中混合列顺序。知道为什么吗?
test.csv
BadMethodCallException in Builder.php line 2003: Call to undefined method Illuminate\Database\Query\Builder::dispensed_drugs()
脚本
animal,age,count,legs
dogs,3,5,4
cats,6,4,4
birds,2,1,2
test.json
import csv
import json
csvfile = open('test.csv', 'r')
jsonfile = open('test.json', 'w')
reader = csv.DictReader( csvfile)
jsonfile.write('[')
for row in reader:
json.dump(row, jsonfile)
jsonfile.write(',\n')
jsonfile.write(']')
答案 0 :(得分:4)
这是因为字典没有任何秩序感,所以预期字典是任意顺序。
如果你必须保留订单(理想情况下你不应该这样做),你需要使用一个简单的csv阅读器读取每一行,然后创建collection.OrderedDict
个对象,这些对象确实存储了键的顺序被添加。示例 -
from collections import OrderedDict
import csv
with open('test.csv','r') as f:
reader = csv.reader(f)
headerlist = next(reader)
csvlist = []
for row in reader:
d = OrderedDict()
for i, x in enumerate(row):
d[headerlist[i]] = x
csvlist.append(d)
import json
with open('test.json','w') as f:
json.dump(csvlist,f)
请注意,如果使用此JSON的解析器不以相同的方式遵守订单,那么这仍然是无用的。
示例/演示 -
将test.csv
作为 -
animal,age,count,legs
dogs,3,5,4
cats,6,4,4
birds,2,1,2
test.json
看起来像 -
[{"animal": "dogs", "age": "3", "count": "5", "legs": "4"},
{"animal": "cats", "age": "6", "count": "4", "legs": "4"},
{"animal": "birds", "age": "2", "count": "1", "legs": "2"}]
答案 1 :(得分:4)
在Anand的回答中,你只是暂时解决问题。 JSON文件可能以正确的顺序输出,但是您可以在另一个位置(例如浏览器或其他Python进程)读取此数据,并且当它读入此文件时,订单将不会被保留!
如果您想保证数据源与目的地之间的订单,则需要使用列表列表。
您可以执行以下操作以保留顺序:
import csv
import json
lst = []
csvfile = open('test.csv', 'r')
jsonfile = open('test.json', 'w')
first_line = next(csvfile).split(',')
csvfile.seek(0) # we peeked at the first_line, lets reset back to beginning
reader = csv.DictReader(csvfile)
for row in reader:
group = []
for h in first_line:
h = h.strip()
group.append([h, row[h]])
lst.append(group)
jsonfile.write(json.dumps(lst))
输出:
[[["animal", "dogs"], ["age", "3"], ["count", "5"], ["legs", "4"]], [["animal", "cats"], ["age", "6"], ["count", "4"], ["legs", "4"]], [["animal", "birds"], ["age", "2"], ["count", "1"], ["legs", "2"]]]