Python 3,让json对象接受字节或让urlopen输出string

与Python3我要求从一些URL一个JSON文件。

response = urllib.request.urlopen(request) 

response对象是一个类似read,readline函数的对象。

通常情况下,一个JSON对象可以创build一个文件(以textmode打开)

 obj = json.load(fp) 

我想要做的是:

 obj = json.load(response) 

但是这不起作用,因为urlopen以二进制模式返回文件对象。

解决方法当然是:

 str_response = response.readall().decode('utf-8') obj = json.loads(str_response) 

但是这感觉很糟糕…

有没有更好的方法,我可以将字节文件对象转换为string文件对象? 或者我错过任何urlopenjson.load参数给一个编码?

这在我看来是一个常见的用例,所以我相信我错过了一些有用的function。

HTTP发送字节。 如果有问题的资源是文本,则通常通过Content-Type HTTP头或其他机制(RFC,HTML meta http-equiv ,…)指定字符编码。

urllib 应该知道如何将字节编码为一个string,但这太天真了 – 这是一个可怕的动力不足和非Pythonic库。

深入Python 3提供了有关情况的概述。

你的“解决方法”很好 – 虽然感觉不对,但这是正确的方法。

Python的美妙标准库来拯救…

 import codecs reader = codecs.getreader("utf-8") obj = json.load(reader(response)) 

适用于py2和py3。

我认为这个问题是最好的答案:)

 import json from urllib.request import urlopen response = urlopen("site.com/api/foo/bar").read().decode('utf8') obj = json.loads(response) 

对于任何尝试使用requests库来解决此问题的人:

 import json import requests r = requests.get('http://localhost/index.json') r.raise_for_status() # works for Python2 and Python3 json.loads(r.content.decode('utf-8')) 

这一个为我工作,我用json()请求'库检查在人类请求文档

 import requests url = 'here goes your url' obj = requests.get(url).json() 

刚刚发现这个简单的方法,使HttpResponse内容为JSON

 import json request = RequestFactory() # ignore this, this just like your request object response = MyView.as_view()(request) # got response as HttpResponse object response.render() # call this so we could call response.content after json_response = json.loads(response.content.decode('utf-8')) print(json_response) # {"your_json_key": "your json value"} 

希望能帮助你

我遇到了类似的问题使用Python 3.4.3&3.5.2和Django 1.11.3。 但是,当我升级到Python 3.6.1时,问题就消失了。

你可以在这里阅读更多关于它的信息: https : //docs.python.org/3/whatsnew/3.6.html#json

如果你没有绑定到特定的Python版本,只要考虑升级到3.6或更高版本。

如果在使用烧瓶微框架的时候遇到这个问题,那么你可以这样做:

data = json.loads(response.get_data(as_text=True))

从文档 :“如果as_text设置为True返回值将是一个解码的Unicodestring”