Phil Jones
Phil Jones

Reputation: 37

Navigating through a JSON with multiples arrays in Python

I'm trying to go through a JSON by using python but I can't access the "mbid" node. I want to print only the first "mbid" node.

Here is my function :

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

With this function i get this error : IndexError: list index out of range

but when I'm doing

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

And print(mbid), I'm getting a correct answer :

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

So means I don't have a problem with the data. Maybe I'm doing something wrong with the second array?

Here is an example of the JSON structure :

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

Thanks for your time

Upvotes: 0

Views: 69

Answers (1)

Pavan Kumar T S
Pavan Kumar T S

Reputation: 1559

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"]

Upvotes: 2

Related Questions