How to print a variable with Requests and JSON

user1198805 picture user1198805 · Jan 27, 2013 · Viewed 25.6k times · Source

I've been programming an application that pulls information from an online API, and I need some help with it.

I'm using requests, and my current code is as follows

myData = requests.get('theapiwebsitehere.com/thispartisworking')
myRealData = myData.json()
x = myRealData['data']['playerStatSummaries']['playerStatSummarySet']['maxRating']
print x

I then get this error

myRealData = myData.json()                                                                                                                      
TypeError: 'NoneType' object is not callable

I want to be able to get to the variable maxRating, and print it out, but I can't seem to do that.

Thanks for your help.

Answer

Burhan Khalid picture Burhan Khalid · Jan 27, 2013

Two things, first, make sure you are using the latest version of requests (its 1.1.0); in previous versions json is not a method but a property.

>>> r = requests.get('https://api.github.com/users/burhankhalid')
>>> r.json['name']
u'Burhan Khalid'
>>> requests.__version__
'0.12.1'

In the latest version:

>>> import requests
>>> requests.__version__
'1.1.0'
>>> r = requests.get('https://api.github.com/users/burhankhalid')
>>> r.json()['name']
u'Burhan Khalid'
>>> r.json
<bound method Response.json of <Response [200]>>

But, the error you are getting is because your URL isn't returning valid json, and you are trying to call on None, what is returned by the property:

>>> r = requests.get('http://www.google.com/')
>>> r.json # Note, this returns None
>>> r.json()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable

In conclusion:

  1. Upgrade your version of requests (pip install -U requests)
  2. Make sure your URL returns valid JSON