我正在使用请求模块和 python assert 关键字设置请求断言,但得到了
AttributeError: 'dict' object has no attribute 'documentation_url'
当我尝试在 json 响应中断言一个字符串时。我如何在 json 响应中断言某些内容,当条件为真时,它应该打印出一些内容?
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'
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.'
}
最佳答案
您好,因为它是一本字典,所以您必须使用键获取值。
我们知道 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
如果你尝试打印出 response['documentation_url']
那么你会得到这样的结果:
https://developer.github.com/v3/activity/events/#list-public-events
关于json - 如何修复 'AttributeError: ' dict' object has no attribute ...' python 断言中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55679929/