从请求库解析 JSON 响应的最佳方法是什么? [英] What's the best way to parse a JSON response from the requests library?
问题描述
我正在使用 python requests
模块 将 RESTful GET 发送到一个服务器,我得到一个 JSON 响应.JSON 响应基本上只是一个列表列表.
I'm using the python requests
module to 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.
强制响应原生 Python 对象以便我可以使用 pprint
迭代或打印它的最佳方法是什么?
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
?
推荐答案
您可以使用 json.loads
:
You can use json.loads
:
import json
import requests
response = requests.get(...)
json_data = json.loads(response.text)
这会将给定的字符串转换为字典,从而允许您在代码中轻松访问 JSON 数据.
This converts a given string into a dictionary which allows you to access your JSON data easily within your code.
或者你可以使用@Martijn 的有用建议,以及更高票的答案,response.json()
.
Or you can use @Martijn's helpful suggestion, and the higher voted answer, response.json()
.
这篇关于从请求库解析 JSON 响应的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!