Iterate Through Nested Json Object using Python
Last Updated :
22 Feb, 2024
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)
OutputUsing 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)
OutputUsing 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)
OutputUsing 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)
OutputUsing json.dumps
name: John
age: 30
address: {'city': 'New York', 'zip': '10001'}
Similar Reads
Python To Generate Dynamic Nested Json String JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. In Python, working with dynamic nested JSON strings is a common task, especially when dealing with complex data structures. In this artic
3 min read
Convert String to JSON Object - Python The goal is to convert a JSON string into a Python dictionary, allowing easy access and manipulation of the data. For example, a JSON string like {"name": "John", "age": 30, "city": "New York"} can be converted into a Python dictionary, {'name': 'John', 'age': 30, 'city': 'New York'}, which allows y
2 min read
Extract Multiple JSON Objects from one File using Python Python is extremely useful for working with JSON( JavaScript Object Notation) data, which is a most used format for storing and exchanging information. However, it can become challenging when dealing with multiple JSON objects stored within a single file. In this article, we will see some techniques
3 min read
Parsing Json Nested Dictionary Using Python We are given a JSON string and we have to parse a nested dictionary from it using different approaches in Python. In this article, we will see how we can parse nested dictionary from a JSON object using Python. Example: Input: json_data = '{"name": "John", "age": 30, "address": {"city": "New York",
2 min read
How to Parse Nested JSON in Python We are given a nested JSON object and our task is to parse it in Python. In this article, we will discuss multiple ways to parse nested JSON in Python using built-in modules and libraries like json, recursion techniques and even pandas.What is Nested JSONNested JSON refers to a JSON object that cont
3 min read