json - 如何修复 'AttributeError: ' dict' object has no attribute ...' python 断言中的错误

标签 json python-3.x assert

我正在使用请求模块和 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/

相关文章:

html - mailchimp 3.0 以html形式获取模板

json - 如何从 nsdictionary swift 获取数组

python-3.x - Matplotlib - 带日期的水平条形图时间线 - Xticks 不显示日期

python - 比较两个以不同方式缩放或以不同方式压缩的相似图像

python - 加载存储在 BytesIO 对象中的 json 文件的正确方法是什么?

java - 如何在android中使用 Volley 发送参数数组

java - 从 JAVA 内部 JSON 对象读取

c++ - 断言为好友类

c - 在 C 中构建时断言表达式的方法

java - 使用 hamcrest 检查列表是否包含特定顺序的类实例