Python 如何使用请求和 JSON 打印变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14543570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:47:38  来源:igfitidea点击:

How to print a variable with Requests and JSON

pythonjsonobjectpython-requestsnonetype

提问by user1198805

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

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

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.

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

Thanks for your help.

谢谢你的帮助。

回答by Matt Alcock

Firstly is myData actually returning anything?

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

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

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

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

导入 Json 包并在文本上使用 Json 加载功能。

import json
newdata = json.loads(myData.text())

回答by Burhan Khalid

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

两件事,首先,确保您使用的是最新版本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'

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:

但是,您收到的错误是因为您的 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

In conclusion:

综上所述:

  1. Upgrade your version of requests(pip install -U requests)
  2. Make sure your URL returns valid JSON
  1. 升级您的requests( pip install -U requests)版本
  2. 确保您的 URL 返回有效的 JSON