How to Parse Nested JSON in Python - GeeksforGeeks (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:

  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 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.

Python3
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.

Python3
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))
How to Parse Nested JSON in Python - GeeksforGeeks (2024)
Top Articles
Key Person Protection | Business Protection | Legal & General
Parenting a Child with a Disability
No Hard Feelings Showtimes Near Metropolitan Fiesta 5 Theatre
Where are the Best Boxing Gyms in the UK? - JD Sports
55Th And Kedzie Elite Staffing
Genesis Parsippany
Georgia Vehicle Registration Fees Calculator
سریال رویای شیرین جوانی قسمت 338
My Vidant Chart
Phillies Espn Schedule
Trini Sandwich Crossword Clue
Classroom 6x: A Game Changer In The Educational Landscape
Panorama Charter Portal
Pizza Hut In Dinuba
Gopher Hockey Forum
Yard Goats Score
Beryl forecast to become an 'extremely dangerous' Category 4 hurricane
Milanka Kudel Telegram
Aps Day Spa Evesham
Self-Service ATMs: Accessibility, Limits, & Features
Yosemite Sam Hood Ornament
Ou Class Nav
JVID Rina sauce set1
Orange Park Dog Racing Results
Best Laundry Mat Near Me
Perry Inhofe Mansion
Otis Offender Michigan
What Happened To Father Anthony Mary Ewtn
Justin Mckenzie Phillip Bryant
Tyler Sis 360 Boonville Mo
Iban's staff
Craigslist West Seneca
Dr. John Mathews Jr., MD – Fairfax, VA | Internal Medicine on Doximity
Adam Bartley Net Worth
Indiana Jones 5 Showtimes Near Cinemark Stroud Mall And Xd
התחבר/י או הירשם/הירשמי כדי לראות.
Bob And Jeff's Monticello Fl
Cnp Tx Venmo
Mcalister's Deli Warrington Reviews
Sallisaw Bin Store
Grizzly Expiration Date Chart 2023
Expendables 4 Showtimes Near Malco Tupelo Commons Cinema Grill
My Eschedule Greatpeople Me
Frequently Asked Questions
Greatpeople.me Login Schedule
Nurses May Be Entitled to Overtime Despite Yearly Salary
Evil Dead Rise - Everything You Need To Know
Craigslist Sarasota Free Stuff
Rocket Bot Royale Unblocked Games 66
Helpers Needed At Once Bug Fables
Osrs Vorkath Combat Achievements
Dr Seuss Star Bellied Sneetches Pdf
Latest Posts
Article information

Author: Cheryll Lueilwitz

Last Updated:

Views: 5776

Rating: 4.3 / 5 (54 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Cheryll Lueilwitz

Birthday: 1997-12-23

Address: 4653 O'Kon Hill, Lake Juanstad, AR 65469

Phone: +494124489301

Job: Marketing Representative

Hobby: Reading, Ice skating, Foraging, BASE jumping, Hiking, Skateboarding, Kayaking

Introduction: My name is Cheryll Lueilwitz, I am a sparkling, clean, super, lucky, joyous, outstanding, lucky person who loves writing and wants to share my knowledge and understanding with you.