我正在向返回 JSON 文件的 URL 发出请求,
\n\nresponse = requests.get(url)\nresponse = json.loads(response)\nRun Code Online (Sandbox Code Playgroud)\n\n然后,我尝试查看一些数据,
\n\nfor documents in response["docs"]:\n # do something\nRun Code Online (Sandbox Code Playgroud)\n\n现在,我得到的错误是
\n\nTypeError: the JSON object must be str, not \'Response\'\nRun Code Online (Sandbox Code Playgroud)\n\n为了避免这种情况,我尝试过,
\n\nresponse = requests.get(url).json()\nRun Code Online (Sandbox Code Playgroud)\n\n但是,我无法遍历响应,因为我收到错误:
\n\nKeyError: \'docs\'\nRun Code Online (Sandbox Code Playgroud)\n\n我是 Python 新手,并不完全了解获取 JSON 数据并解析它的最佳方法。建议?
\n\n这是接收到的数据的示例,
\n\n\n\n{\'状态\': \'确定\', \'响应\': {\'元\': {\'时间\': 9, \'点击数\': 11, \'偏移量\': 0 }, \'docs\': [{\'type_of_material\': \'新闻\', \'pub_date\': \'2017-01-01T09:12:04+0000\', \'document_type\': \'article\', \'_id\': \'5868c7e995d0e03926078885\', \'lead_paragraph\': \'国家\xe2\x80\x99的领导人自豪地谈到其核武器和弹道导弹计划的进展。\ ',......
\n
您正在尝试将响应对象提供给json.loads(). 您在那里没有得到字符串,您必须访问.contentsor.text属性:
response = requests.get(url)
# Python 3
response = json.loads(response.text)
# Python 2
response = json.loads(response.content)
Run Code Online (Sandbox Code Playgroud)
然而,这会做比你需要的更多的工作;requests支持直接处理JSON,无需导入json模块:
response = requests.get(url).json()
Run Code Online (Sandbox Code Playgroud)
请参阅快速入门文档的JSON 响应内容部分requests。
加载后,您可以获取嵌套字典doc中的键:response
for documents in response['response']['docs']:
Run Code Online (Sandbox Code Playgroud)