Open In App

How to Parse Nested JSON in Python

Last Updated : 07 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We are given a nested JSON object and our task is to parse the nested JSON in Python using different approaches. In this article, we will see how we can parse nested JSON in Python.

Example:

Input: nested_json_data = '{"name": "John", "age": 30, "address": {"city": "New York", "zipcode": "10001"}}'
Output: Name: John, Age: 30
Explanation: Here, we are parsing the name and age from the nested JSON.

Parse Nested JSON in Python

Below are some of the ways by which we can parse nested JSON in Python:

  1. Using the JSON module
  2. Using Recursion
  3. Using the Pandas library

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.

Python3




import json
 
# Sample nested JSON data
nested_json_data = '{"name": "John", "age": 30, "address": {"city": "New York", "zipcode": "10001"}}'
 
# Parse JSON data
parsed_data = json.loads(nested_json_data)
 
# Accessing nested values
name = parsed_data['name']
age = parsed_data['age']
city = parsed_data['address']['city']
zipcode = parsed_data['address']['zipcode']
 
# Printing the results
print(f"Name: {name}")
print(f"Age: {age}")
print(f"City: {city}")
print(f"Zipcode: {zipcode}")


Output

Name: John
Age: 30
City: New York
Zipcode: 10001

Using Recursion

In this example, the parse_json function employs 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.

Python3




import json
 
# Sample nested JSON data
nested_json_data = '{"person": {"name": "John", "age": 30, "address": {"city": "New York", "zipcode": "10001"}}}'
 
def parse_json(data):
    result = {}
    for key, value in data.items():
        if isinstance(value, dict):
            result[key] = parse_json(value)
        else:
            result[key] = value
    return result
 
# Parsing JSON data using recursion
parsed_data = parse_json(json.loads(nested_json_data))
 
# Accessing nested values
name = parsed_data['person']['name']
age = parsed_data['person']['age']
city = parsed_data['person']['address']['city']
zipcode = parsed_data['person']['address']['zipcode']
 
# Printing the results
print(f"Name: {name}")
print(f"Age: {age}")
print(f"City: {city}")
print(f"Zipcode: {zipcode}")


Output

Name: John
Age: 30
City: New York
Zipcode: 10001

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.’ Finally, the extracted values are printed as lists, showcasing a convenient way to work with nested JSON data in a tabular format using Pandas.

Python3




import pandas as pd
import json
 
# Sample nested JSON data
nested_json_data = '{"employees": [{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]}'
 
# Parsing JSON data using pandas
df = pd.json_normalize(json.loads(nested_json_data), 'employees')
 
# Accessing dataframe columns
names = df['name']
ages = df['age']
 
# Printing the results
print("Names:", list(names))
print("Ages:", list(ages))


Output:

Names: ['John', 'Jane'] 
Ages: [30, 25]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads