python - 请求模块返回带有无序项目的 json

标签 python python-requests

当我以这种方式使用 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/

相关文章:

python 3 : using requests does not get the full content of a web page

python - PyQt5 加载微调器在发布请求时停止

python - 从子类变量访问父类变量

python - 客户端 服务器端实时物体检测

python - 模块未找到错误 : No module named 'pyasn1'

python - Boost Python,Visual Studio 链接到错误的 boost dll

Python 请求抛出 SSL 错误

python 使用 cookie 请求登录

python - 在文本中查找大量短语的出现

python - 解析请求响应的键、值对