【发布时间】: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
dictimplementation was introduced that preserved insertion order,但是这种行为不受语言的保证。从 Python 3.7 开始,现在保证dictkeeps insertion order。这应该避免显式使用OrderedDict。