如何使用Requests和JSON打印变量

use*_*805 10 python json object python-requests nonetype

我一直在编写一个从在线API中提取信息的应用程序,我需要一些帮助.

我正在使用请求,我目前的代码如下

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

然后我得到这个错误

myRealData = myData.json()                                                                                                                      
TypeError: 'NoneType' object is not callable
Run Code Online (Sandbox Code Playgroud)

我希望能够获得变量maxRating,并将其打印出来,但我似乎无法做到这一点.

谢谢你的帮助.

Bur*_*lid 22

两件事,首先,确保您使用的是最新版本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'
Run Code Online (Sandbox Code Playgroud)

在最新版本中:

>>> 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]>>
Run Code Online (Sandbox Code Playgroud)

但是,您得到的错误是因为您的URL没有返回有效的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
Run Code Online (Sandbox Code Playgroud)

结论:

  1. 升级你的requests(pip install -U requests)版本
  2. 确保您的URL返回有效的JSON


Mat*_*ock 1

首先,myData 实际上返回了什么吗?

如果是,那么您可以尝试以下操作,而不是使用 .json() 函数

导入 Json 包并在文本上使用 Json 加载函数。

import json
newdata = json.loads(myData.text())
Run Code Online (Sandbox Code Playgroud)