Strange python problem, 'unicode' object does not have 'read' attribute

Here is my code and does anyone have any ideas what is wrong? I open my JSON content directly with the browser and it works,

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

+7
json python unicode python-requests
source share
2 answers

This error occurs because data is a unicode / str variable, change the second line of code to solve your error:

 data = json.loads(data) 

json.load get the file object at the position of the first parameter and call the read method of this.

You can also call the json response method to directly retrieve the data:

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

requests.get(…).text returns the contents as a single line (unicode). However, the json.load() function requires a file argument.

The solution is pretty simple: just use loads instead of load :

 data = json.loads(data) 

An even better solution is to simply call json() directly in the response object. Therefore, do not use .text , but .json() :

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

Although this uses json.loads internally, it hides this implementation detail, so you can just focus on getting a JSON response.

+2
source share

All Articles