当我以这种方式使用 python 的 requests
模块时:
response = requests.get('http://[some_api_url]')
打印 response.json()
与通过浏览器查看 json 相反,我得到了不同的 json。
例如:
通过 response.json() 我得到:
[{"key2":"value2"},{"key1:"value1"}]
而通过浏览器我认为它应该是:
[{"key1:"value1"},{"key2":"value2"}]
编辑: 以正确的顺序打印 response.text
时
但不是json
最佳答案
您可以按照 doc 中的建议使用 json 模块的 object_pairs_hook
参数:
object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, collections.OrderedDict() will remember the order of insertion). If object_hook is also defined, the object_pairs_hook takes priority.
import json
from collections import OrderedDict
result = json.loads(request.text,
object_pairs_hook=OrderedDict)
为了更简单,您可以在 implementation of requests 中看到kwargs 从 json 方法传递到 json 模块,因此这也有效:
d = response.json(object_pairs_hook=OrderedDict)
和 d
将是 OrderedDict
并保留 response.text
的顺序。
关于python - 请求模块返回带有无序项目的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35042216/