在尝试解析某些json时,我一直收到以下错误:
Traceback (most recent call last):
File "/Users/batch/projects/kl-api/api/helpers.py", line 37, in collect_youtube_data
keywords = channel_info_response_data['items'][0]['brandingSettings']['channel']['keywords']
KeyError: 'brandingSettings'
如何确保在将键分配给变量之前检查JSON输出?如果找不到键,那么我只想指定一个默认值。代码如下:
^{pr2}$
假设您有一个dict,您有两个选项来处理key not exist情况:
1)获取具有默认值的密钥,例如
val
将为10,因为没有名为k
的密钥2)尝试例外
^{pr2}$这种方法更灵活,因为您可以在
except
块中执行任何操作,甚至可以忽略pass
语句的错误,如果您真的不在乎它的话。在你可以把你的作业打包成
或者,假设使用
.has_key(...)
。依我看,在你的情况下,第一个解决方案是最好的此时,“JSON输出”只是一个普通的原生Python
dict
现在您知道您有一个
dict
,浏览dict
方法的官方文档应该可以回答以下问题:https://docs.python.org/3/library/stdtypes.html#dict.get
所以一般情况是:
现在,如果您有深度嵌套的dict/list,其中可能缺少任何键或索引,那么捕捉KeyErrors和indexerErrors会更简单:
^{pr2}$另请注意:代码片段中充满了重复的
channel_info_response_data['items'][0]['statistics']
和channel_info_response_data['items'][0]['snippet']
表达式。使用中间变量将使代码更易读、更易于维护,并且速度更快:您可能还想了解字符串格式(连续的字符串很容易出错,几乎不可读),以及how to pass arguments to ^{}
相关问题 更多 >
编程相关推荐