Open In App

Iterate Through Nested Json Object using Python

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Working with nested JSON objects in Python can be a common task, especially when dealing with data from APIs or complex configurations. In this article, we’ll explore some generally used methods to iterate through nested JSON objects using Python.

Iterate Through Nested Json Object

Below, are the method of Iterate Through Nested JSON Object in Python.

Iterate Through Nested Json Object Using For Loop

In this example, the Python code defines a function, `iterate_nested_json_for_loop`, which uses a for loop to recursively iterate through a nested JSON object and print key-value pairs.

Python3




# Using For Loop
def iterate_nested_json_for_loop(json_obj):
    for key, value in json_obj.items():
        if isinstance(value, dict):
            iterate_nested_json_for_loop(value)
        else:
            print(f"{key}: {value}")
 
# Example usage with a nested JSON object
nested_json = {
    "name": "John",
    "age": 30,
    "address": {
        "city": "New York",
        "zip": "10001"
    }
}
 
print("Using For Loop")
iterate_nested_json_for_loop(nested_json)


Output

Using For Loop
name: John
age: 30
city: New York
zip: 10001



Iterate Through Nested Json Object Using List Comprehension

In this example, the Python code defines a function, `iterate_nested_json_list_comprehension`, which utilizes list comprehension to recursively iterate through a nested JSON object, creating a list of tuples containing key-value pairs.

Python3




# Using List Comprehension
def iterate_nested_json_list_comprehension(json_obj):
    items = [(key, value) if not isinstance(value, dict) else (key, iterate_nested_json_list_comprehension(value)) for key, value in json_obj.items()]
    return items
 
# Example usage with a nested JSON object
nested_json = {
    "name": "John",
    "age": 30,
    "address": {
        "city": "New York",
        "zip": "10001"
    }
}
 
print("\nUsing List Comprehension")
result = iterate_nested_json_list_comprehension(nested_json)
print(result)


Output

Using List Comprehension
[('name', 'John'), ('age', 30), ('address', [('city', 'New York'), ('zip', '10001')])]



Iterate Through Nested Json Object Using Recursive Function

In this example, the below Python code employs a recursive function, `iterate_nested_json_recursive`, using a traditional approach with a for loop to traverse through a nested JSON object and print its key-value pairs.

Python3




import json
 
# Using Recursive Function
def iterate_nested_json_recursive(json_obj):
    for key, value in json_obj.items():
        if isinstance(value, dict):
            iterate_nested_json_recursive(value)
        else:
            print(f"{key}: {value}")
 
# Example usage with a nested JSON object
nested_json = {
    "name": "John",
    "age": 30,
    "address": {
        "city": "New York",
        "zip": "10001"
    }
}
 
print("\nUsing Recursive Function")
iterate_nested_json_recursive(nested_json)


Output

Using Recursive Function
name: John
age: 30
city: New York
zip: 10001



Iterate Through Nested Json Object Using json.dumps() Method

In this example, the below Python code utilizes `json.dumps` to flatten a nested JSON object into a string and then uses `json.loads` to convert it back into a dictionary. It then iterates through the flattened dictionary, printing key-value pairs.

Python3




import json
 
# Using json.loads with json.dumps
def iterate_nested_json_flatten(json_obj):
    flattened_json_str = json.dumps(json_obj)
    flattened_json = json.loads(flattened_json_str)
 
    for key, value in flattened_json.items():
        print(f"{key}: {value}")
 
# Example usage with a nested JSON object
nested_json = {
    "name": "John",
    "age": 30,
    "address": {
        "city": "New York",
        "zip": "10001"
    }
}
 
print("\nUsing json.dumps")
iterate_nested_json_flatten(nested_json)


Output

Using json.dumps
name: John
age: 30
address: {'city': 'New York', 'zip': '10001'}





Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads