奇怪的python问题,'unicode'对象没有'read'属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32040541/
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
strange python issue, 'unicode' object has no attribute 'read'
提问by Lin Ma
Here is my code and does anyone have any ideas what is wrong? I open my JSON contentdirectly by browser and it works,
这是我的代码,有没有人知道有什么问题?我直接通过浏览器打开我的 JSON 内容,它可以工作,
data = requests.get('http://ws.audioscrobbler.com/2.0/?method=library.getartists&api_key=4c22bd45cf5aa6e408e02b3fc1bff690&user=joanofarctan&format=json').text
data = json.load(data)
print type(data)
return data
thanks in advance, Lin
提前致谢,林
采纳答案by M.javid
This error raised because the data
is a unicode/str variable, change the second line of your code to resolve your error:
引发此错误data
是因为它是 unicode/str 变量,请更改代码的第二行以解决错误:
data = json.loads(data)
json.load
get a file object in first parameter position and call the read
method of this.
json.load
在第一个参数位置获取一个文件对象并调用read
this的方法。
Also you can call the json
method of the response to fetch data directly:
您也可以调用json
响应的方法直接获取数据:
response = requests.get('http://ws.audioscrobbler.com/2.0/?method=library.getartists&api_key=4c22bd45cf5aa6e408e02b3fc1bff690&user=joanofarctan&format=json')
data = response.json()
回答by poke
requests.get(…).text
returns the content as a single (unicode) string. The json.load()
function however requires a file-like argument.
requests.get(…).text
将内容作为单个(unicode)字符串返回。json.load()
然而,该函数需要一个类似文件的参数。
The solution is rather simple: Just use loads
instead of load
:
解决方案相当简单:只需使用loads
代替load
:
data = json.loads(data)
An even better solution though is to simply call json()
on the response object directly. So don't use .text
but .json()
:
更好的解决方案是直接调用json()
响应对象。所以不要使用.text
但是.json()
:
data = requests.get(…).json()
While this uses json.loads
itself internally, it hides that implementation detail, so you can just focus on getting the JSON response.
虽然json.loads
它在内部使用自身,但它隐藏了实现细节,因此您可以专注于获取 JSON 响应。