user2657983
user2657983

Reputation:

Parsing JSON Array using Python Requests & Error Codes

I'm attempting to parse a JSON array, however, I'm having some issues. Here's my current code:

from django.http import HttpResponse
import json, requests
platformUrl = 'https://www.igbd.com/api/v1/platforms'
platformReq = requests.get(platformUrl, headers={'Authorization': 'Token token="1234"'})
platformData = json.loads(platformReq)#json.loads(platformReq.text)
platformList = data['platforms']

print platformList

The example output is:

{"platforms":[{"id":32,"name":"Sega Saturn","slug":"saturn"},{"id":14,"name":"Mac","slug":"mac"},{"id":47,"name":"Virtual Console (Nintendo)","slug":"vc"}

I'm getting error:

expected string or buffer

When I use this code, it works, but the output is wrong, and it's not meant for arrays:

from django.http import HttpResponse
import json, requests

platformUrl = 'https://www.igdb.com/api/v1/platforms'
platformReq = requests.get(platformUrl, headers={'Authorization': 'Token token=1234"'})
platformData = platformReq.json()

print platformData

Here is the output with that code:

{u'platforms': [{u'slug': u'saturn', u'id': 32, u'name': u'Sega Saturn'}, {u'slug': u'mac', u'id': 14, u'name': u'Mac'}, {u'slug': u'vc', u'id': 47, u'name': u'Virtual Console (Nintendo)'}

Bonus question: How would I handle errors for the request? Ex: 200 - everything's fine, 401 - not valid key, etc, etc...

Any help would be appreciated.

Upvotes: 2

Views: 7876

Answers (2)

Paul Oostenrijk
Paul Oostenrijk

Reputation: 659

It is because you pass an request object in the json.loads

In the error it says that it needs a string or buffer instead. You can pass in the string from the request by doing:

json.loads(platformReq.text)

But platformReq.json() works the same way!

Hope that helps.

EDIT

To respond to your status code question (sorry didn't see it before). You can check the response status code like this:

if platformReq.status_code == requests.codes.ok:
    # Print the response
    print platformReq.json()
else:
    print "Something went wrong";

Upvotes: 3

siracoj
siracoj

Reputation: 101

If you are expecting a JSON response, the code that you have commented out should work:

    json.loads(platformReq.text)

The error you are getting is because json.loads() needs a string, not a response object.

As for the error handling I would recommend adding a check at the top of this for platformReg.status_code to make sure that it is equal to 200 before you proceed

Upvotes: 1

Related Questions