Parse json in python when as dict when only one "node"

139 Views Asked by At

I am able to parse json ressponse when there are multiple "nodes" of what I am looking for, but when only one node is returned by the API, I am getting the message "string indices must be integers". Here is my code in which I am pass in the dictionary after converting it from a string using json.loads():

import requests, requests.auth
import json
import os

def parseSchedule(dict):
    i = 0
    for item in dict['reservations']['reservation']:
        print(item['event_start_dt'])
        i += 1

I've simplified the json response to show that this works:

    {
    "reservations": {
        "reservation": [{
            "event_start_dt": "2019-11-27T12:40:00-08:00"
        }, {
            "event_start_dt": "2019-11-27T16:10:00-08:00"
        }]
    }
}

While this throws the error "string indices must be integers":

    {
    "reservations": {
        "reservation": {
            "event_start_dt": "2019-11-26T08:30:00-08:00"   
        }
    }
}

I have researched the .items() in which I attempt the key and value but have been unsuccessful thus far.

1

There are 1 best solutions below

1
On

You can do it with something like this:

#If it is a list:
if str(type(dict["reservations"]["reservation"])) == "<class 'list'>":
    for i in range(len(dict["reservations"]["reservation"])):
        print(dict["reservations"]["reservation"][i]["event_start_dt"])
else: #If it is not a list
    print(dict['reservations']['reservation']['event_start_dt'])