Ant*_*296 1 json assert python-3.x
我正在使用请求模块和python assert关键字设置请求断言,但是
AttributeError:'dict'对象没有属性'documentation_url'
当我尝试在json响应中声明字符串时。我如何在json响应中声明某些内容,当条件为true时,它应该打印出某些内容?
import requests
import pprint
URL = 'https://github.com/timeline.json'
def get_github_json(URL):
response = requests.get(URL).json()
return response
assert get_github_json(URL).documentation_url == 'https://developer.github.com/v3/activity/events/#list-public-events'
Run Code Online (Sandbox Code Playgroud)
json响应如下所示:
{'documentation_url': 'https://developer.github.com/v3/activity/events/#list-public-events',
'message': 'Hello there, wayfaring stranger. If you’re reading this then you '
'probably didn’t see our blog post a couple of years back '
'announcing that this API would go away: http://git.io/17AROg Fear '
'not, you should be able to get what you need from the shiny new '
'Events API instead.'
}
Run Code Online (Sandbox Code Playgroud)
嗨,因为它是字典,所以您必须使用键来获取值。
我们知道这response是一个字典,因此在这种情况下,当您想要来自的值时documentation_url,我们需要这样做:
def get_github_json(url):
response = requests.get(url).json()
return response
assert get_github_json(url)['documentation_url'] # <---- your are getting the value by giving the key
Run Code Online (Sandbox Code Playgroud)
如果尝试打印出来response['documentation_url'],则会得到以下结果:
https://developer.github.com/v3/activity/events/#list-public-events