JSON 对象和 Python 字典都是无序的。为了保持顺序,请使用映射到 Python 列表的 JSON 数组。JSON 数组的元素应该是 JSON 对象。这些将映射到 Python 字典的 Python 列表。
蟒蛇 3:
from collections import OrderedDict
import json
# Preserving order in Python dict:
ordered_dict = OrderedDict([
('a', 1),
('b', 2),
('c', 3),
])
# Convert to JSON while preserving order:
ordered_list = [{key: val} for key, val in ordered_dict.items()]
json.dumps(ordered_list)
# '[{"a": 1}, {"b": 2}, {"c": 3}]'
Javascript(JSON):
var orderedListStr = '[{"a": 1}, {"b": 2}, {"c": 3}]';
// We will receive this array of objects with preserved order:
var orderedList = JSON.parse(orderedListStr)