如何使用Requests和JSON打印变量
我正在编写一个应用程序,这个程序可以从网上的API获取信息,我需要一些帮助。
我在用requests库,下面是我现在的代码:
myData = requests.get('theapiwebsitehere.com/thispartisworking')
myRealData = myData.json()
x = myRealData['data']['playerStatSummaries']['playerStatSummarySet']['maxRating']
print x
然后我遇到了这个错误:
myRealData = myData.json()
TypeError: 'NoneType' object is not callable
我想获取变量maxRating,并把它打印出来,但我似乎做不到。
谢谢你的帮助。
2 个回答
1
首先,myData真的有返回任何东西吗?
如果有返回的话,你可以试试下面的方法,而不是使用.json()这个函数。
导入Json包,然后在文本上使用Json的loads函数。
import json
newdata = json.loads(myData.text())
23
有两件事,首先,确保你使用的是最新版本的 requests
(现在是1.1.0);在之前的版本中,json
不是一个方法,而是一个属性。
>>> r = requests.get('https://api.github.com/users/burhankhalid')
>>> r.json['name']
u'Burhan Khalid'
>>> requests.__version__
'0.12.1'
在最新版本中:
>>> 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]>>
不过,你遇到的错误是因为你的网址没有返回有效的 JSON 数据,而你试图调用的是 None
,这就是属性返回的结果:
>>> 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
总结一下:
- 升级你的
requests
版本(使用pip install -U requests
) - 确保你的网址返回有效的 JSON 数据