JSON对象必须是str,而不是Response [英] JSON object must be str, not Response

查看:240
本文介绍了JSON对象必须是str,而不是Response的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在请求返回JSON文件的URL,

I'm making a request to a URL that returns a JSON file,

response = requests.get(url)
response = json.loads(response)

然后,我尝试浏览一些数据,

And then, I am attempting to go through some of the data,

for documents in response["docs"]:
    # do something

现在,我得到的错误是

TypeError: the JSON object must be str, not 'Response'

为了避免这种情况,我尝试过

In order to avoid this, I tried,

response = requests.get(url).json()

但是,由于出现错误,我无法遍历响应:

But then, I can't traverse the response because I get the error:

KeyError: 'docs'

我是Python的新手,并不完全了解获取JSON数据并解析它的最佳方法.有建议吗?

I'm new to Python and not fully aware of the best way to get JSON data and parse it. Suggestions?

这里是接收到的数据的样本,

Here is a sample of the data being received,

{'status':'OK','response':{'meta':{'time':9,'hits':11,'offset':0},'docs':[{'type_of_material' :'新闻','pub_date':'2017-01-01T09:12:04 + 0000','document_type':'article','_id':'5868c7e995d0e03926078885','lead_paragraph':'该国领导人自豪地谈到核武器和弹道导弹计划的进展.',.....

{'status': 'OK', 'response': {'meta': {'time': 9, 'hits': 11, 'offset': 0}, 'docs': [{'type_of_material': 'News', 'pub_date': '2017-01-01T09:12:04+0000', 'document_type': 'article', '_id': '5868c7e995d0e03926078885', 'lead_paragraph': 'The country’s leader spoke proudly of the progress of its nuclear weapons and ballistic missile programs.', .....

推荐答案

您正在尝试将响应对象提供给json.loads().您在那里没有字符串,而必须访问.contents.text属性:

You are trying to feed the response object to json.loads(). You don't get a string there, you'd have to access the .contents or .text attribute instead:

response = requests.get(url)
# Python 3
response = json.loads(response.text)
# Python 2
response = json.loads(response.content)

但是,这样做的工作量超出了您的需要; requests支持直接处理JSON,无需导入json模块:

However, that'd be doing more work than you need to; requests supports handling JSON directly, and there is no need to import the json module:

response = requests.get(url).json()

请参见 JSON响应内容requests快速入门文档的部分.

See the JSON Response Content section of the requests Quickstart documentation.

加载后,您可以在嵌套词典中的doc键上键入response:

Once loaded, you can get the doc key in the nested dictionary keyed on response:

for documents in response['response']['docs']:

这篇关于JSON对象必须是str,而不是Response的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆