【问题标题】:requests module return json with items unordered请求模块返回带有无序项目的 json
【发布时间】:2017-02-18 16:00:11
【问题描述】:

当我以这种方式使用 python 的 requests 模块时:

response = requests.get('http://[some_api_url]') print response.json() 与通过浏览器查看 json 相反,我得到了不同的 json。

例如:
通过 response.json() 我得到:
[{"key2":"value2"},{"key1:"value1"}]

而通过浏览器,我认为它应该是: [{"key1:"value1"},{"key2":"value2"}]

编辑:打印response.text时,它的顺序正确 但不是json

【问题讨论】:

  • 可以发一下网址吗?
  • 很遗憾,它不是公共 URL
  • 我通常使用:json.loads(response.text parse_float=float, object_pairs_hook=OrderedDict),OrderedDict 来自collections
  • @stellasia:谢谢,我自己找到了这个解决方案,但是有没有办法以有序的方式使用 requests.json()?
  • 在 CPython 3.6 中是 new dict implementation was introduced that preserved insertion order,但是这种行为不受语言的保证。从 Python 3.7 开始,现在保证 dict keeps insertion order。这应该避免显式使用OrderedDict

标签: python python-requests


【解决方案1】:

您可以按照doc 中的建议使用json 模块的object_pairs_hook 参数:

object_pairs_hook 是一个可选函数,将调用使用有序对列表解码的任何对象文字的结果。将使用 object_pairs_hook 的返回值而不是 dict。此功能可用于实现依赖于键值对解码顺序的自定义解码器(例如,collections.OrderedDict() 将记住插入顺序)。如果还定义了 object_hook,则 object_pairs_hook 优先。

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 的顺序。

【讨论】:

  • 我用d = response.json(object_pairs_hook=OrderedDict)验证了第二种方法,效果很好。
  • 请将 object_parir_hook 改为 object_pairs_hook
  • 哇,这非常有帮助。不知道没有这个我是怎么过去的。谢谢楼主!
猜你喜欢
  • 2014-05-02
  • 1970-01-01
  • 2017-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-26
  • 1970-01-01
相关资源
最近更新 更多