user9406886
user9406886

Reputation:

Navigation through json (python)

I'm trying to navigation through a json file but cannot parse properly the 'headliner' node.

Here is my JSON file :

{  
   "resultsPage":{  
      "results":{  
         "calendarEntry":[  
            {
              "event":{  
                 "id":38862824,
                 "artistName":"Raphael",
               },
               "performance":[  
                  {  
                     "id":73632729,
                     "headlinerName":"Top-Secret",
                  }
               }
            ],
            "venue":{  
               "id":4285819,
               "displayName":"Sacré"
            }
         }
      }
   }

Here is what I my trying to do :

for item in data ["resultsPage"]["results"]["calendarEntry"]:
    artistname = item["event"]["artistName"]
    headliner = item["performance"]["headlinerName"]

I don't understand why it's working for the 'artistName' but it's not working for 'headlinerName'. Thanks for your help and your explanation.

Upvotes: 2

Views: 211

Answers (2)

user1532172
user1532172

Reputation:

A few problems here. First, your JSON is incorrectly formatted. Your square brackets don't match up. Maybe you meant something like this? I am going to assume "calendarEntry" is a list here and everything else is an object. Usually lists are made plural, i.e. "calendarEntries".

{  
   "resultsPage": {
      "results": {  
         "calendarEntries": [  
            {
              "event": {  
                 "id": 38862824,
                 "artistName": "Raphael"
               },
               "performance": {
                  "id": 73632729,
                  "headlinerName": "Top-Secret"
               },
               "venue": {  
                  "id": 4285819,
                  "displayName": "Sacré"
               }
            }
         ]
      }
   }
}

Upvotes: 0

R4444
R4444

Reputation: 2114

Notice your performance key:

"performance":[  
                  {  
                     "id":73632729,
                     "headlinerName":"Top-Secret",
                  }
               }
            ],

The json you posted is malformed. Assuming the structure is like:

"performance":[  
                      {  
                         "id":73632729,
                         "headlinerName":"Top-Secret",
                      }

              ],

You can do:

for i in item:
    i["headlinerName"]

or as @UltraInstinct suggested:

item["performance"][0]["headlinerName"]

Upvotes: 1

Related Questions