使用 sort_keys 指定排序
使用 sort_keys 参数指定结果是否应该排序
以下实例为学习使用 sort_keys 参数指定结果是否应该排序,具体代码如下:
# Filename : example.py
# Author by : www.lidihuo.com
import json
x = {
"name": "Bill",
"age": 63,
"married": True,
"divorced": False,
"children": ("Jennifer","Rory","Phoebe"),
"pets": None,
"cars": [
{"model": "Porsche", "mpg": 38.2},
{"model": "BMW M5", "mpg": 26.9}
]
}
# sort the result alphabetically by keys:
print(json.dumps(x, indent=4, sort_keys=True))
执行以上代码输出结果为:
# Filename : example.py
# Author by : www.lidihuo.com
{
"age": 63,
"cars": [
{
"model": "Porsche",
"mpg": 38.2
},
{
"model": "BMW M5",
"mpg": 26.9
}
],
"children": [
"Jennifer",
"Rory",
"Phoebe"
],
"divorced": False,
"married": true,
"name": "Bill",
"pets": null
}