奇怪的 python 问题,'unicode' 对象没有属性 'read'

strange python issue, 'unicode' object has no attribute 'read'

这是我的代码,有人知道哪里出了问题吗?我直接用浏览器打开my JSON content就可以了,

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

提前致谢, 林

出现此错误是因为 data 是一个 unicode/str 变量,请更改代码的第二行以解决您的错误:

data = json.loads(data)

json.load在第一个参数位置获取一个文件对象,并调用此read方法。

也可以直接调用response的json方法获取数据:

response = requests.get('http://ws.audioscrobbler.com/2.0/?method=library.getartists&api_key=4c22bd45cf5aa6e408e02b3fc1bff690&user=joanofarctan&format=json')
data = response.json()

requests.get(…).text returns the content as a single (unicode) string. The json.load() 函数需要一个类似文件的参数。

解决方案很简单:只需使用 loads 而不是 load:

data = json.loads(data)

更好的解决方案是直接在响应对象上简单地调用 json()。所以不要使用 .text.json():

data = requests.get(…).json()

虽然这在内部使用 json.loads 本身,但它隐藏了实现细节,因此您可以只专注于获取 JSON 响应。