【发布时间】:2015-08-22 17:32:59
【问题描述】:
基本的 Python csv 到 json 脚本在最终的 JSON 中混合列顺序。知道为什么吗?
test.csv
animal,age,count,legs
dogs,3,5,4
cats,6,4,4
birds,2,1,2
脚本
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(']')
test.json
[{"count": "5", "age": "3", "legs": "4", "animal": "dogs"},
{"count": "4", "age": "6", "legs": "4", "animal": "cats"},
{"count": "1", "age": "2", "legs": "2", "animal": "birds"},
]
【问题讨论】:
-
您可以使用它来获取有序字典pymotw.com/2/collections/ordereddict.html
-
json 未排序。也不是python dict。
-
@njzk2 就
Object.keys(json[0])而言 -
@geotheory 这只是一个巧合。不要依赖那个。 (您还会注意到小整数在
set中排序,但这并不意味着其他键也会如此)