Last Updated : 07 Mar, 2024
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.
Below are some of the ways by which we can parse nested JSON in Python:
- Using the JSON module
- Using Recursion
- 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.
import json# Sample nested JSON datanested_json_data = '{"name": "John", "age": 30, "address": {"city": "New York", "zipcode": "10001"}}'# Parse JSON dataparsed_data = json.loads(nested_json_data)# Accessing nested valuesname = parsed_data['name']age = parsed_data['age']city = parsed_data['address']['city']zipcode = parsed_data['address']['zipcode']# Printing the resultsprint(f"Name: {name}")print(f"Age: {age}")print(f"City: {city}")print(f"Zipcode: {zipcode}")
Output
Name: JohnAge: 30City: New YorkZipcode: 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.
import json# Sample nested JSON datanested_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 recursionparsed_data = parse_json(json.loads(nested_json_data))# Accessing nested valuesname = parsed_data['person']['name']age = parsed_data['person']['age']city = parsed_data['person']['address']['city']zipcode = parsed_data['person']['address']['zipcode']# Printing the resultsprint(f"Name: {name}")print(f"Age: {age}")print(f"City: {city}")print(f"Zipcode: {zipcode}")
Output
Name: JohnAge: 30City: New YorkZipcode: 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.
import pandas as pdimport json# Sample nested JSON datanested_json_data = '{"employees": [{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]}'# Parsing JSON data using pandasdf = pd.json_normalize(json.loads(nested_json_data), 'employees')# Accessing dataframe columnsnames = df['name']ages = df['age']# Printing the resultsprint("Names:", list(names))print("Ages:", list(ages))