collections.OrderedDict 无法处理 json.dump()
collections.OrderedDict not working on json.dump()
我没有正确使用它,因为它没有产生我想要的顺序:
import json
from collections import OrderedDict
dict_1 = {}
dict_2 = {}
metadata = {
'id': 1,
'columns': [dict_1],
'dtypes': [dict_2],
}
with open('metadata.json', 'w') as metadata_dumped :
json.dump(metadata, metadata_dumped, sort_keys=True, indent=4, separators=(',', ': '), object_pairs_hook=OrderedDict)
我已经按照我想要输出的顺序编码了 id
和 2 dictionaries
。
但输出文件的最后 2 个 dictionaries
位于 .json.
之上
我的想法哪里出了问题? 'standard' 的解决方案是什么?
根据the documentation,sort_keys
将对键进行排序,而不是保留顺序。
If sort_keys is true (default: False), then the output of dictionaries will be sorted by key.
我没有正确使用它,因为它没有产生我想要的顺序:
import json
from collections import OrderedDict
dict_1 = {}
dict_2 = {}
metadata = {
'id': 1,
'columns': [dict_1],
'dtypes': [dict_2],
}
with open('metadata.json', 'w') as metadata_dumped :
json.dump(metadata, metadata_dumped, sort_keys=True, indent=4, separators=(',', ': '), object_pairs_hook=OrderedDict)
我已经按照我想要输出的顺序编码了 id
和 2 dictionaries
。
但输出文件的最后 2 个 dictionaries
位于 .json.
我的想法哪里出了问题? 'standard' 的解决方案是什么?
根据the documentation,sort_keys
将对键进行排序,而不是保留顺序。
If sort_keys is true (default: False), then the output of dictionaries will be sorted by key.