【问题标题】:json KeyError - how to parse json outputjson KeyError - 如何解析 json 输出
【发布时间】:2023-01-11 17:55:23
【问题描述】:

早上好,我有一个关于解析 json 数据的问题,问题是我无法通过键解析它。顺便说一句,我刚开始使用 python ...这是我的代码:

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)

这是一个输出:

{'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'}]}}}}}

我需要阅读所有“名称”问题是当我尝试做这样的事情时:

 print(a['name'])

我收到 KeyError。是否有可能添加键或任何其他方法来只读取“名称”值?

【问题讨论】:

  • 你在找a.data.actor.entitySearch.results.entities[0].name吗?
  • 所有“名称”值
  • @subodhkalika 该语法不适用于字典

标签: python json


【解决方案1】:

你必须浏览字典。您需要在层次结构中某处找到具有键“名称”的字典。

键“名称”出现在示例数据的多个位置。因此递归方法可能是要走的路:

a = {'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'}]}}}}}


def parse(d):
    if isinstance(d, dict):
        if 'name' in d:
            print(d['name'])
        else:
            for v in d.values():
                parse(v)
    else:
        if isinstance(d, list):
            for e in d:
                parse(e)


parse(a)

输出:

C
C / C Overview
C / Errors
C / Transactions
C / VM Metrics
Customer experience bottom of the funnel analysis
Customer experience bottom of the funnel analysis / BOFU - Desktop
Customer experience bottom of the funnel analysis / BOFU - Mobile and other
FirstOne
FirstOne / FirstOne
FirstOne-clone
FirstOne-clone / FirstOne

【讨论】:

  • 这就是我需要的。非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2016-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多