【问题标题】:Navigating through a JSON with multiples arrays in Python在 Python 中导航具有多个数组的 JSON
【发布时间】:2019-11-11 09:40:10
【问题描述】:

我正在尝试使用 python 处理 JSON,但我无法访问“mbid”节点。我只想打印第一个“mbid”节点。

这是我的功能:

def get_data():
    newJsonx = dict()
    for item in data["resultsPage"]["results"]["calendarEntry"]:
        mbid = item["event"]["performance"][0]["artist"]["identifier"][0]["mbid"]

使用这个函数我得到这个错误:IndexError: list index out of range

但是当我在做的时候

def get_data():
    newJsonx = dict()
    for item in data["resultsPage"]["results"]["calendarEntry"]:
        mbid = item["event"]["performance"][0]["artist"]["identifier"]

还有print(mbid),我得到了正确答案:

"identifier": [
  {
   "mbid": "6655955b-1c1e-4bcb-84e4-81bcd9efab30"
  },
  {
   "mbid": "1b1b1b1b-1c1d"
  }
]

所以意味着我的数据没有问题。也许我对第二个数组做错了什么?

以下是 JSON 结构的示例:

{
  "resultsPage": {
    "status": "ok",
    "results": {
      "calendarEntry": [
        {
          "reason": {

          },
          "event": {
            "performance": [
              {
                "id": 72641494,
                "displayName": "Arnalds",
                "artist": {
                  "id": 590465,
                  "identifier": [
                    {
                      "mbid": "6655955b-1c1e-4bcb-84e4-81bcd9efab30"
                    },
                    {                   
                      "mbid": "1b1b1b1b-1c1d"
                    }
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  }
}

感谢您的宝贵时间

【问题讨论】:

  • 您的第一个函数适用于您的示例。
  • 无法复制,对我来说工作正常,您的完整数据 JSON 必须缺少一些值或为空列表,这导致 [0] 给您错误
  • @OferSadan 你是对的,有时我有空列表

标签: python json python-3.x api


【解决方案1】:
def get_data():
    newJsonx = dict()
    for item in data["resultsPage"]["results"]["calendarEntry"]:
        performance=item["event"]["performance"]
        if performace:
          identifier=performace[0]["artist"]["identifier"]
          if identifier:
            mbid=identifier[0]["mbid"]

【讨论】:

    猜你喜欢
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    相关资源
    最近更新 更多