使用Python中的OrderedDict和sorted函数来对JSON文件进行排序。
示例代码:
import json
from collections import OrderedDict
# 读取JSON文件并将其转换为OrderedDict格式
with open('example.json', 'r') as f:
data = json.load(f, object_pairs_hook=OrderedDict)
# 对OrderedDict进行排序
sorted_data = OrderedDict(sorted(data.items()))
# 将排序后的数据写入新的JSON文件中
with open('sorted_example.json', 'w') as f:
f.write(json.dumps(sorted_data, indent=4))
在此示例中,我们首先使用json模块读取example.json文件并将其转换为有序字典格式。然后,我们使用sorted函数对有序字典进行排序,并将其存储在sorted_data变量中。最后,我们使用json.dump函数将排序后的数据写入新的JSON文件中。
下一篇:按外部分组列的内部查询