15

Here is my code and does anyone have any ideas what is wrong? I open my JSON content directly by 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

2
  • 4
    drop the json.load, requests objects have a .json() method. Commented Aug 16, 2015 at 22:29
  • Please remember to upvote helpful answers and accept the one that solved your problem to mark this question as resolved. Commented Aug 16, 2015 at 22:43

2 Answers 2

39

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

data = json.loads(data)

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

Also you can call the json method of the response to fetch data directly:

response = requests.get('http://ws.audioscrobbler.com/2.0/?method=library.getartists&api_key=4c22bd45cf5aa6e408e02b3fc1bff690&user=joanofarctan&format=json')
data = response.json()
Sign up to request clarification or add additional context in comments.

2 Comments

Using json.loads (with the 's' at the end) instead of json.load fixrd my issue
Is there any particular preference between the two working solutions ? data = response.json() vs data = json.loads(data) ?
4

requests.get(…).text returns the content as a single (unicode) string. The json.load() function however requires a file-like argument.

The solution is rather simple: Just use loads instead of 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():

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.

1 Comment

urgh just notice I had missed the "s" THANKS!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.