beaconhill
beaconhill

Reputation: 451

Looping through all JSON children

Right now I have a for loop that looks one by one for whether the key value == a variable.

I'm doing this one by one by selecting the [0] and [1] index to get the first two children. There could be up to four children, is there a more efficient way to do this than elif?

# INITIALIZE NEW FILTERED DICTIONARY (RETAINING TOP LEVEL ITEMS)
    newdata = OrderedDict({k:v for k,v in data.items() if k in ['stop_id', 'stop_name']})
    newdata['mode'] = []
    arrivalarray = []

    # ITERATE CONDITIONALLY KEEPING NEEDED SECTIONS
    for i in data['mode']:
        if i['route'][0]['route_name'] == line:
            if i['route'][0]['direction'][0]['direction_name'] == direction:
                for s in i['route'][0]['direction'][0]['trip']:
                    arrivalarray.append(s['pre_away'])
            elif i['route'][0]['direction'][1]['direction_name'] == direction:
                for s in i['route'][0]['direction'][1]['trip']:
                    arrivalarray.append(s['pre_away'])

Upvotes: 1

Views: 1384

Answers (2)

alpheus
alpheus

Reputation: 240

Well yes, you could use recursion instead of iteration and that is actually what DFS is.

def traverse_json(json, depth): 
    if depth = 0 :
        return [];
    else:
        data = [];
        for i in json.keys():
             if isinstance(json[i], dict):
                  data += traverse_json(json[i], depth -1)
             else :
                  data.append(json[i])
        return data

You could start with the max depth you require.

Upvotes: 1

glibdud
glibdud

Reputation: 7870

Once you've loaded the JSON data, it's no longer JSON data. It's just a nested series of Python lists, dicts, strings, etc. As such, you can do what you'd do for any Python data structure, such as use a for loop to iterate over the elements of a list:

for d in i['route'][0]['direction']:
    if d['direction_name'] == direction:
        for s in d['trip']:
            arrivalarray.append(s['pre_away'])

Upvotes: 0

Related Questions