[英]How to get urllib2 response in json
I have the following code: 我有以下代码:
import urllib2
response = urllib2.urlopen('http://python.org/')
What would be the most straightforward way to get this in json
? 在
json
最简单的方法是什么?
The output of " http://python.org/ " is not returning json documents. “ http://python.org/ ”的输出未返回json文档。
You can check the types of your output as below: 您可以检查输出的类型,如下所示:
>>> import urllib2
>>> response = urllib2.urlopen('http://python.org/')
>>> response.headers.type
'text/html'
>>>
OK, lets see one example of json response api: 好的,让我们看一个json响应api的示例:
>>> response = urllib2.urlopen('http://api.icndb.com/jokes/random')
>>> response.headers.type
'application/json'
>>>
So, here in the header type you can see the 'application/json' which means that the reponse contain json documents. 因此,在标题类型中,您可以看到“ application / json”,这意味着响应包含json文档。
>>> import json
>>> json_docs = json.load(response)
>>> print json_docs
{u'type': u'success', u'value': {u'joke': u'How many Chuck Norris require to screw a light bulb? None, he will screw it all.', u'id': 562, u'categories': []}}
>>>
Given a response object, you would do 给定一个响应对象,您将
jsondata = json.load(response)
Of course, you will be fetching data from a URL that is actually JSON data ( http://python.org/
is not JSON). 当然,您将从实际是JSON数据的URL中获取数据(
http://python.org/
不是JSON)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.