How to print a variable with Requests and JSON

28,111

Solution 1

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

Solution 2

Firstly is myData actually returning anything?

If it is then you can try the following rather than work with the .json() function

Import the Json package and use the Json loads function on the text.

import json
newdata = json.loads(myData.text())
Share:
28,111
Admin
Author by

Admin

Updated on January 27, 2020

Comments

  • Admin
    Admin over 4 years

    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.

  • Burhan Khalid
    Burhan Khalid over 11 years
    requests already decodes the json into python objects, another reason to love it.
  • Matt Alcock
    Matt Alcock over 11 years
    Yes but services sometimes return the Json with the wrong headers I've found this secondary approach a good fall back
  • lkraav
    lkraav almost 11 years
    Yeap, old version of Requests was my problem.