转换为 json 重新排序 python 中的对象

Converting to json re-orders objects in python

我正在尝试使用请求在 python 中从 http://steamcommunity.com/profiles/76561198081591043/inventory/json/730/2 获得响应。

import requests    
url =  "http://steamcommunity.com/profiles/76561198081591043/inventory/json/730/2"   
r = requests.get(url)
print r.text
print r.json()

r.textr.json() return 对象排序不同。 例如,在 'rgInventory' 中,.text 中的前 3 个 "ids":925, 658, 891 结尾,但在 .json() 中以 891, 619, 741 结尾(只是巧合正在下降)。

json.loads(r.text) 产生相同的结果

如何让 json 对象与 .text 显示的顺序相同?

JSON 对象未按照 javascript 的定义排序(Does JavaScript Guarantee Object Property Order?). To get the desired result, you would have to sort the resulting dictionary by keys: How can I sort a dictionary by key?

JSON 对象中字段的顺序显然没有意义,不需要保留。为了提高效率,许多实现都是哈希表。

如果 JSON 顺序很重要,您 必须 使用数组——在这种情况下,最简单的模型可能是一个包含双元素数组的数组,每个数组依次包含一个字符串名称和一个值。

另一种解决方案是使用非 JSON 字符串处理代码将 JSON 对象字段按您的首选顺序进行处理。不推荐!

抱歉,规范无法识别的差异根本就不是差异。

这可能是不必要的,如果有必要,要么是您的代码或 Steam API 有问题。从您的评论来看,这可能是不必要的。也就是说,这是可行的。

json.loads 采用可选的 object_pairs_hook 参数。这指定了一个函数,该函数将使用键值对列表调用以解码对象文字。默认相当于指定object_pairs_hook=dict;要保留键在原始文本中出现的顺序,您可以使用 object_pairs_hook=collections.OrderedDict:

import collections, json
data = json.loads(response_string, object_pairs_hook=collections.OrderedDict)

r.json() 将关键字参数传递给 json.loads,因此它应该支持相同的参数:

data = r.json(object_pairs_hook=collections.OrderedDict)