Python 从请求库解析 JSON 响应的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16877422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the best way to parse a JSON response from the requests library?
提问by felix001
I'm using the python requestsmoduleto send a RESTful GET to a server, for which I get a response in JSON. The JSON response is basically just a list of lists.
我正在使用 pythonrequests模块将 RESTful GET 发送到服务器,我收到 JSON 格式的响应。JSON 响应基本上只是一个列表列表。
What's the best way to coerce the response to a native Python object so I can either iterate or print it out using pprint?
强制响应本机 Python 对象以便我可以使用 迭代或打印它的最佳方法是什么pprint?
采纳答案by Simeon Visser
You can use json.loads:
您可以使用json.loads:
import json
import requests
response = requests.get(...)
json_data = json.loads(response.text)
This converts a given string into a dictionary which allows you to access your JSON data easily within your code.
这会将给定的字符串转换为字典,允许您在代码中轻松访问 JSON 数据。
Or you can use @Martijn's helpful suggestion, and the higher voted answer, response.json().
或者您可以使用@Martijn 的有用建议,以及更高投票的答案response.json().
回答by pswaminathan
Since you're using requests, you should use the response's jsonmethod.
由于您正在使用requests,您应该使用响应的json方法。
import requests
response = requests.get(...)
data = response.json()

