python - 检查来自 json 输出的键是否存在
问题描述
尝试解析一些 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 输出?如果找不到键,那么我只想分配一个默认值。下面的代码:
try:
channel_id = channel_id_response_data['items'][0]['id']
channel_info_url = YOUTUBE_URL + '/channels/?key=' + YOUTUBE_API_KEY + '&id=' + channel_id + '&part=snippet,contentDetails,statistics,brandingSettings'
print('Querying:', channel_info_url)
channel_info_response = requests.get(channel_info_url)
channel_info_response_data = json.loads(channel_info_response.content)
no_of_videos = int(channel_info_response_data['items'][0]['statistics']['videoCount'])
no_of_subscribers = int(channel_info_response_data['items'][0]['statistics']['subscriberCount'])
no_of_views = int(channel_info_response_data['items'][0]['statistics']['viewCount'])
avg_views = round(no_of_views / no_of_videos, 0)
photo = channel_info_response_data['items'][0]['snippet']['thumbnails']['high']['url']
description = channel_info_response_data['items'][0]['snippet']['description']
start_date = channel_info_response_data['items'][0]['snippet']['publishedAt']
title = channel_info_response_data['items'][0]['snippet']['title']
keywords = channel_info_response_data['items'][0]['brandingSettings']['channel']['keywords']
except Exception as e:
raise Exception(e)
解决方案
假设你有一个 dict,你有两个选项来处理 key-not-exist 的情况:
1)获取具有默认值的键,例如
d = {}
val = d.get('k', 10)
val
将是 10,因为没有名为的键k
2) 尝试除外
d = {}
try:
val = d['k']
except KeyError:
val = 10
这种方式更加灵活,因为你可以在块中做任何事情,如果你真的不关心它except
,甚至可以用语句忽略错误。pass
推荐阅读
- ios - UITextField 没有通过键盘启动移动到正确的位置
- python - 计算几个 DataFrame 的单元格的标准差
- sql - 我们如何获得以特定行开头的一组行?
- c# - 在数据库中输入 Float(输入更多数字) C# Microsoft SQL Server
- templates - .NET Core 多项目模板 - 重命名项目参考
- python-3.x - Pandas - 使用 to_csv 附加到现有文件
- stm32 - NUCLEO-H743ZI2 lwIP TCP 连接
- r - 旋转 xlabels 并将 x 轴标题与标签分离
- ios - UIScrollView/UIStackView - 内容太短时拉伸
- c - C中字符串结构变量中的错误赋值