Python urllib2:从 url 接收 JSON 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13921910/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:56:52  来源:igfitidea点击:

Python urllib2: Receive JSON response from url

pythonjsonurllib2

提问by Deepak B

I am trying to GET a URL using Python and the response is JSON. However, when I run

我正在尝试使用 Python 获取 URL,响应是 JSON。然而,当我跑

import urllib2
response = urllib2.urlopen('https://api.instagram.com/v1/tags/pizza/media/XXXXXX')
html=response.read()
print html

The html is of type str and I am expecting a JSON. Is there any way I can capture the response as JSON or a python dictionary instead of a str.

html 是 str 类型,我期待一个 JSON。有什么方法可以将响应捕获为 JSON 或 python 字典而不是 str.json 。

采纳答案by Martijn Pieters

If the URL is returning valid JSON-encoded data, use the jsonlibraryto decode that:

如果 URL 返回有效的 JSON 编码数据,请使用json库对其进行解码:

import urllib2
import json

response = urllib2.urlopen('https://api.instagram.com/v1/tags/pizza/media/XXXXXX')
data = json.load(response)   
print data

回答by MostafaR

Be careful about the validation and etc, but the straight solution is this:

小心验证等,但直接的解决方案是:

import json
the_dict = json.load(response)

回答by SanalBathery

import json
import urllib

url = 'http://example.com/file.json'
r = urllib.request.urlopen(url)
data = json.loads(r.read().decode(r.info().get_param('charset') or 'utf-8'))
print(data)

urllib, for Python 3.4
HTTPMessage, returned by r.info()

urllib,用于 Python 3.4
HTTPMessage,由 r.info() 返回

回答by Jossef Harush

resource_url = 'http://localhost:8080/service/'
response = json.loads(urllib2.urlopen(resource_url).read())

回答by Uxbridge

None of the provided examples on here worked for me. They were either for Python 2 (uurllib2) or those for Python 3 return the error "ImportError: No module named request". I google the error message and it apparently requires me to install a the module - which is obviously unacceptable for such a simple task.

此处提供的示例均不适合我。它们要么用于 Python 2 (uurllib2),要么用于 Python 3 返回错误“ImportError: No module named request”。我谷歌了错误消息,它显然要求我安装一个模块——这对于这样一个简单的任务显然是不可接受的。

This code worked for me:

这段代码对我有用:

import json,urllib
data = urllib.urlopen("https://api.github.com/users?since=0").read()
d = json.loads(data)
print (d)

回答by Nitigya Sharma

Though I guess it has already answered I would like to add my little bit in this

虽然我猜它已经回答了我想在这个中添加我的一点点

import json
import urllib2
class Website(object):
    def __init__(self,name):
        self.name = name 
    def dump(self):
     self.data= urllib2.urlopen(self.name)
     return self.data

    def convJSON(self):
         data=  json.load(self.dump())
     print data

domain = Website("https://example.com")
domain.convJSON()

Note : object passed to json.load()should support .read(), therefore urllib2.urlopen(self.name).read()would not work . Doamin passed should be provided with protocol in this case http

注意:传递给json.load() 的对象应该支持.read(),因此urllib2.urlopen(self.name).read()将不起作用。在这种情况下,Doamin 通过的协议应该提供给http

回答by raccoon

"""
Return JSON to webpage
Adding to wonderful answer by @Sanal
For Django 3.4
Adding a working url that returns a json (Source: http://www.jsontest.com/#echo)
"""

import json
import urllib

url = 'http://echo.jsontest.com/insert-key-here/insert-value-here/key/value'
respons = urllib.request.urlopen(url)
data = json.loads(respons.read().decode(respons.info().get_param('charset') or 'utf-8'))
return HttpResponse(json.dumps(data), content_type="application/json")

回答by Adam

Python 3 standard library one-liner:

Python 3 标准库单行:

load(urlopen(url))

# imports (place these above the code before running it)
from json import load
from urllib.request import urlopen
url = 'https://jsonplaceholder.typicode.com/todos/1'

回答by Haritsinh Gohil

you can also get json by using requestsas below:

您还可以使用requests以下方法获取 json :

import requests

r = requests.get('http://yoursite.com/your-json-pfile.json')
json_response = r.json()

回答by Himanshu Aggarwal

This is another simpler solution to your question

这是您问题的另一个更简单的解决方案

pd.read_json(data)

where data is the str output from the following code

其中 data 是以下代码的 str 输出

response = urlopen("https://data.nasa.gov/resource/y77d-th95.json")
json_data = response.read().decode('utf-8', 'replace')