A universal JSON traverser in Python

16 Mar 2015


As a purely academic exercise, I set out on finding a simple solution to a problem that had been bugging me for some days:

What would a universal JSON traverser be like?

The traverser has to go through each and every key pair value and print the value assigned.

So I came up with this semi-recursive solution. I don’t feel it is elegant enough, although this is the best I could do for now. I am looking into better ways for a proper tree search which JSON traversal is all about.

def traverse_dict(json_data):
    for value in json_data.itervalues():
        if isinstance(value, dict):
            traverse_dict(value)
        elif isinstance(value, list):
            traverse_list(value)
        else:
            print_element(value)


def traverse_list(data_list):
    for item in data_list:
        if isinstance(item, dict):
            traverse_dict(item)
        elif isinstance(item, list):
            traverse_list(item)
        else:
            print_element(item)

def print_element(element):
    print "Traversing: " + str(element)

Previous Post Next Post