How to Convert JSON String to Tree Diagram in Python?

How to Convert JSON String to Tree Diagram in Python?

  • Python
  • 3 mins read

A tree diagram is a way of organizing data in a hierarchical manner, with a single node at the top called the root node and any number of nodes below it. Each node in a tree can have any number of children, and the children of a node are organized into a list. The children of a node are referred to as its child nodes, and the node itself is referred to as the parent node. Here is an example of how you can use Python to convert a JSON string into a tree diagram:

JSON String to Tree Diagram in Python Examples

import json

def print_tree(json_obj, indent=0):
    if isinstance(json_obj, dict):
        for key, value in json_obj.items():
            print(" " * indent + str(key))
            print_tree(value, indent+4)
    elif isinstance(json_obj, list):
        for item in json_obj:
            print_tree(item, indent+4)
    else:
        print(" " * indent + str(json_obj))

# Load the JSON string
json_string = '{"name": "John", "age": 30, "city": "New York"}'
json_obj = json.loads(json_string)

# Print the tree
print_tree(json_obj)

This code defines a function print_tree that takes a JSON object and an indentation level as input. It then checks the type of the JSON object. If it is a dictionary, it iterates over the key-value pairs and prints the key with the appropriate indentation, followed by the value. If the value is itself a JSON object, the function is called recursively with the value as the input and an increased indentation level. If the JSON object is a list, the function iterates over the items in the list and prints them with the appropriate indentation. If the JSON object is neither a dictionary nor a list, it is assumed to be a leaf node and is printed with the appropriate indentation.

The output of the print_tree function in this example would be:

name
    John
age
    30
city
    New York

Here is another example to convert JSON string to a tree diagram using Python:

import json

def print_tree(json_obj, indent=0):
    if isinstance(json_obj, dict):
        for key, value in json_obj.items():
            if key == "name":
                print(" " * indent + str(value))
            else:
                print_tree(value, indent+4)
    elif isinstance(json_obj, list):
        for item in json_obj:
            print_tree(item, indent+4)

# Load the JSON string
json_string = '{"name": "Root node", "children": [{"name": "Child node 1", "children": [{"name": "Grandchild node 1", "children": [{"name": "Great-grandchild node 1"}, {"name": "Great-grandchild node 2"}]}, {"name": "Grandchild node 2"}]}, {"name": "Child node 2"}]}'
json_obj = json.loads(json_string)

# Print the tree
print_tree(json_obj)

This version of the print_tree function only prints the "name" field of the JSON object and ignores all other fields. It also increases the indentation level only when it encounters a "children" field, which ensures that the tree diagram is properly indented.

The output of this program would be:

Root node
Child node 1
Grandchild node 1
Great-grandchild node 1
                        Great-grandchild node 2
                Grandchild node 2
        Child node 2

You can also provide the file containing JSON data to Python program, below is an example:

Converting JSON to Tree Diagram Using File as JSON data Source

import json

def print_tree(json_obj, indent=0):
    if isinstance(json_obj, dict):
        for key, value in json_obj.items():
            print(" " * indent + str(key))
            print_tree(value, indent+4)
    elif isinstance(json_obj, list):
        for item in json_obj:
            print_tree(item, indent+4)
    else:
        print(" " * indent + str(json_obj))

# Load the JSON object
with open('json_file.json', 'r') as f:
    json_obj = json.load(f)

# Print the tree
print_tree(json_obj)

Related: