从请求库中解析JSON响应的最佳方法是什么?
我正在使用python request
module 将其发送到服务器,为此,我在JSON中得到了回应。 JSON响应基本上只是列表。
胁迫对本机Python对象的响应的最佳方法是什么,以便我可以使用 pprint
迭代或打印出来?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
由于您正在使用
请求
,因此应使用响应的json
方法。它
Since you're using
requests
, you should use the response'sjson
method.It autodetects which decoder to use.
您可以使用
json.loads
:
这将给定的字符串转换为字典,使您可以在代码中轻松访问JSON数据。
或者,您可以使用 @martijn的有用建议,而较高的投票答案,
wendesp.json()
。You can use
json.loads
:This converts a given string into a dictionary which allows you to access your JSON data easily within your code.
Or you can use @Martijn's helpful suggestion, and the higher voted answer,
response.json()
.您可以直接将JSON响应用作字典:
或者您可以将JSON内容作为字典将其保存为字典:
从此
JSON_RES
字典变量,您可以提取您选择的任何值actentions 因为这是一本词典,所以您应该关注关键拼写,并且情况下, ie“总”与'total''不同
You can use the json response as dictionary directly:
or you can hold the json content as dictionary:
and from this
json_res
dictionary variable, you can extract any value of your choiceAttentions Because this is a dictionary, you should keep your eye on the key spelling and the case, i.e. 'total' is not the same as 'Total'
顶部答案显示似乎是将JSON响应解析为Python对象的两种不同的方法,但它们基本上是相同的。
response.json()
在两个地方有所不同:simplejson
(如果在环境中安装了python 的JSON库的外部维护的开发版本,但是使用inther-in-in-in-injson
(如果不是)( JSON Simplejson 之间的性能差异(当Python 2仍然被广泛使用时),但是库之间几乎没有区别。响应。编码
none),则它试图猜测它并尝试使用猜测编码( source )。因此,在99.9999%的情况下,
wendesp.json()
andjson.loads(wendesp.text)
将产生相同的字典。如果源JSON具有一些怪异的编码,则可能会有所不同。The top answers show seemingly two different ways to parse a json response into a Python object but they are essentially the same.
response.json()
differs in two places:simplejson
(which is the externally maintained development version of the json library included with Python) if it's installed in your environment, but uses the built-injson
if not (source). I think there used to be a performance difference betweenjson
andsimplejson
in the past (when Python 2 was still widely used) but there's almost no difference between the libraries anymore.response.encoding
is None), then it tries to guess it and try to decode using the guessed encoding (source).So in 99.9999% of cases,
response.json()
andjson.loads(response.text)
will produce the same dictionary. It may differ if the source json has some weird encoding.如果不json
in case of not json