首页 > 解决方案 > 检查来自 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)

标签: python

解决方案


假设你有一个 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


推荐阅读