json element tree in python

You can use the json module and the json.load() method to load a JSON object into a Python dictionary. Once you have the JSON object in the form of a dictionary, you can traverse the dictionary using standard Python code to print the element tree.

Here's an example:

main.py
import json

# Load the JSON data from a file
with open('example.json') as f:
    data = json.load(f)

# Define a function to print the element tree
def print_element_tree(element, indent=0):
    for key, value in element.items():
        # Print the key-value pair with indentation
        print('\t' * indent + str(key) + ':')
        # Print the value recursively if it's a nested element (dictionary or list)
        if isinstance(value, dict):
            print_element_tree(value, indent+1)
        elif isinstance(value, list):
            for item in value:
                print_element_tree(item, indent+1)
        # Print the value as-is if it's a leaf node (string, number, boolean, null)
        else:
            print('\t' * (indent+1) + str(value))

# Print the element tree
print_element_tree(data)
816 chars
24 lines

This code will load the JSON data from a file called example.json, traverse the dictionary recursively, and print the element tree with appropriate indentation.

Note that this code assumes that the JSON object is well-formed and does not contain circular references. If you're not sure about the quality of the JSON data, you may need to add additional error-handling code.

related categories

gistlibby LogSnag