[英]How to sort json files by keys
I have a json file, for example, 例如,我有一个json文件,
{
"2":{"name": "A", "Label": "Student"},
"3":{"name": "B", "Label": "Student"},
"1":{"name": "B", "Label": "Student"},
...
}
I want to sort the file by keys, then the result should be: 我想按键对文件排序,那么结果应该是:
"1":{"name": "B", "Label": "Student"},
"2":{"name": "A", "Label": "Student"},
"3":{"name": "B", "Label": "Student"},
...
}
How can I achieve it? 我该如何实现?
Try this, if you want it as JSON 如果您希望将其作为JSON,请尝试一下
import json
json.loads(json.dumps(values, sort_keys=True))
Output 输出量
{"1": {"Label": "Student", "name": "B"}, "2": {"Label": "Student", "name": "A"}, "3": {"Label": "Student", "name": "B"}}
d = {
"2":{"name": "A", "Label": "Student"},
"3":{"name": "B", "Label": "Student"},
"1":{"name": "B", "Label": "Student"},
}
import json
from collections import OrderedDict
print(json.dumps(OrderedDict(sorted(d.items())), indent=4))
Prints: 印刷品:
{
"1": {
"name": "B",
"Label": "Student"
},
"2": {
"name": "A",
"Label": "Student"
},
"3": {
"name": "B",
"Label": "Student"
}
}
EDIT: If your keys are integers encoded as string and you want to sort them ascending: 编辑:如果您的键是编码为字符串的整数,并且您要对它们进行升序排序:
print(json.dumps(OrderedDict(sorted(d.items(), key=lambda k: int(k[0]))), indent=4))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.