How to Parse Nested JSON in Python
Last Updated :
14 Apr, 2025
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 JSON
Nested JSON refers to a JSON object that contains another JSON object (or an array of objects) inside it.
Example:
{
"name": "John",
"age": 30,
"address": {
"city": "New York",
"zipcode": "10001"
}
}
In the above example, address is a nested JSON object.
In this article, we will discuss multiple ways to parse nested JSON in Python. Let's discuss them one by one:
Using the JSON module
In this example, we use the json
module to parse a nested JSON string. Subsequently, we access specific values within the JSON structure using dictionary keys, demonstrating how to retrieve information such as the name, age, city and zipcode.
Python
import json
n_json = '{"name": "Prajjwal", "age": 23, "address": {"city": "Prayagraj", "zipcode": "20210"}}'
data = json.loads(n_json)
name = data['name']
age = data['age']
city = data['address']['city']
zipc = data['address']['zipcode']
print(f"Name: {name}")
print(f"Age: {age}")
print(f"City: {city}")
print(f"Zipcode: {zipc}")
OutputName: Prajjwal
Age: 23
City: Prayagraj
Zipcode: 20210
Explanation:
- json.loads() converts the JSON string into a Python dictionary.
- Nested values (like "city") are accessed using key chaining: data['address']['city'].
- This approach is ideal when the structure of JSON is fixed and known in advance.
Using Recursion
In this example, the parse_json
function uses recursion to traverse the nested JSON structure and create a flattened dictionary. The parsed data is then accessed using keys to retrieve specific values such as name, age, city and zipcode from the original nested JSON data.
Python
import json
n_json = '{"person": {"name": "Prajjwal", "age": 23, "address": {"city": "Prayagraj", "zipcode": "20210"}}}'
# Define a recursive function to parse nested JSON
def parse_json(data):
result = {}
for key, val in data.items():
if isinstance(val, dict):
result[key] = parse_json(val) # Recursive call
else:
result[key] = val
return result
data = parse_json(json.loads(n_json))
name = data['person']['name']
age = data['person']['age']
city = data['person']['address']['city']
zipc = data['person']['address']['zipcode']
print(f"Name: {name}")
print(f"Age: {age}")
print(f"City: {city}")
print(f"Zipcode: {zipc}")
OutputName: Prajjwal
Age: 23
City: Prayagraj
Zipcode: 20210
Explanation:
- parse_json() function recursively navigates each level of the JSON structure.
- This method is helpful when we don't know how deep is the nesting.
- It builds a dictionary with the same nested structure, making it easier to access specific values later.
Using the Pandas library
In this example, the pd.json_normalize
function from the Pandas library is utilized to flatten the nested JSON data into a Pandas DataFrame. The resulting DataFrame, df
, allows easy access to specific columns such as 'name' and 'age.'
Python
import pandas as pd
import json
n_json = '{"employees": [{"name": "Prajjwal", "age": 23}, {"name": "Kareena", "age": 22}]}'
data = json.loads(n_json)
df = pd.json_normalize(data, 'employees')
names = df['name']
ages = df['age']
print("Names:", list(names))
print("Ages:", list(ages))
OutputNames: ['Prajjwal', 'Kareena']
Ages: [23, 22]
Explanation:
- json.loads() first converts the JSON string to a Python object.
- pd.json_normalize() flattens the nested list into a table like structure.
- This is particularly useful for structured data like logs, records or API results with multiple entries.
Also read: Recursion, Python, Pandas, Json.
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read