You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python解析JSON遇KeyError:如何提取嵌套结构中的name字段

问题:提取New Relic GraphQL API返回JSON中的所有name字段值

作为Python初学者,调用New Relic GraphQL API获取到嵌套结构的JSON后,尝试直接用print(a['name'])提取name字段时触发KeyError,需要提取所有name值。

代码示例

nrq_data = {
    'query': '{\n  actor {\n    entitySearch(queryBuilder: {type: DASHBOARD}) {\n      query\n      results {\n        entities {\n          name\n        }\n      }\n    }\n  }\n}\n', 'variables': ''}

nrq_response = requests.post(
    'https://api.eu.newrelic.com/graphql', headers=nrq_headers, json=nrq_data)

a = json.loads(nrq_response.text)

print(a)

返回的JSON结果

{'data': {'actor': {'entitySearch': {'query': "type IN ('DASHBOARD')", 'results': {'entities': [{'name': 'C'}, {'name': 'C / C Overview'}, {'name': 'C / Errors'}, {'name': 'C / Transactions'}, {'name': 'C / VM Metrics'}, {'name': 'Customer experience bottom of the funnel analysis'}, {'name': 'Customer experience bottom of the funnel analysis / BOFU - Desktop'}, {'name': 'Customer experience bottom of the funnel analysis / BOFU - Mobile and other'}, {'name': 'FirstOne'}, {'name': 'FirstOne / FirstOne'}, {'name': 'FirstOne-clone'}, {'name': 'FirstOne-clone / FirstOne'}]}}}}}

解决方案

name字段并非在JSON顶层,而是嵌套在data->actor->entitySearch->results->entities层级的数组元素中,直接访问顶层的name自然会触发KeyError。提取所有name值的方法如下:

基础实现:逐层访问后遍历

# 逐层获取到entities列表
entities = a['data']['actor']['entitySearch']['results']['entities']

# 遍历列表,逐个提取name并打印
for entity in entities:
    print(entity['name'])

# 若需将所有name存入列表,可使用列表推导式
name_list = [entity['name'] for entity in entities]
print(name_list)

稳健实现:避免键缺失报错

如果担心API返回结构变动导致某个键不存在,可以用dict.get()方法兜底,避免KeyError:

# 逐层获取,每个层级都设置默认空值
entities = a.get('data', {}).get('actor', {}).get('entitySearch', {}).get('results', {}).get('entities', [])

# 提取name,若元素中无name则用默认值填充
name_list = [entity.get('name', '未知名称') for entity in entities]
print(name_list)

内容的提问来源于stack exchange,提问作者Martin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 14:35:50