How to Print Nested JSON Data Using Python?

11 minutes read

To print nested JSON data using Python, you can follow the steps below:

  1. Import the required libraries:
1
import json


  1. Load the JSON data from a file or API response:
1
data = json.loads(json_data)


Here, json_data can be the JSON extracted from a file or API response.

  1. Write a function to recursively iterate through the nested JSON data:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def print_json(data, indent=0):
    for key, value in data.items():
        print('\t' * indent + str(key))
        
        if isinstance(value, dict):
            print_json(value, indent + 1)
        elif isinstance(value, list):
            for item in value:
                if isinstance(item, dict):
                    print_json(item, indent + 1)
                else:
                    print('\t' * (indent + 1) + str(item))
                print('\n')
        else:
            print('\t' * (indent + 1) + str(value))
            print('\n')


This function takes the JSON data as input and an optional indent parameter to control the indentation level. Starting with the root object, it recursively iterates through the data, printing each key and value.

  1. Call the print_json function with the loaded JSON data:
1
print_json(data)


This will print the nested JSON data to the console, displaying the keys and values with proper indentation.


By using this approach, you can easily print nested JSON data in a structured manner using Python.

Best Python Books to Read in 2023

1
Learning Python, 5th Edition

Rating is 5 out of 5

Learning Python, 5th Edition

2
Python Programming and SQL: [7 in 1] The Most Comprehensive Coding Course from Beginners to Advanced | Master Python & SQL in Record Time with Insider Tips and Expert Secrets

Rating is 4.9 out of 5

Python Programming and SQL: [7 in 1] The Most Comprehensive Coding Course from Beginners to Advanced | Master Python & SQL in Record Time with Insider Tips and Expert Secrets

3
Introducing Python: Modern Computing in Simple Packages

Rating is 4.8 out of 5

Introducing Python: Modern Computing in Simple Packages

4
Python for Data Analysis: Data Wrangling with pandas, NumPy, and Jupyter

Rating is 4.7 out of 5

Python for Data Analysis: Data Wrangling with pandas, NumPy, and Jupyter

5
Python Programming for Beginners: Ultimate Crash Course From Zero to Hero in Just One Week!

Rating is 4.6 out of 5

Python Programming for Beginners: Ultimate Crash Course From Zero to Hero in Just One Week!

6
Python All-in-One For Dummies (For Dummies (Computer/Tech))

Rating is 4.5 out of 5

Python All-in-One For Dummies (For Dummies (Computer/Tech))

7
Python Crash Course, 3rd Edition: A Hands-On, Project-Based Introduction to Programming

Rating is 4.4 out of 5

Python Crash Course, 3rd Edition: A Hands-On, Project-Based Introduction to Programming

8
Python Programming for Beginners: The Complete Guide to Mastering Python in 7 Days with Hands-On Exercises – Top Secret Coding Tips to Get an Unfair Advantage and Land Your Dream Job!

Rating is 4.3 out of 5

Python Programming for Beginners: The Complete Guide to Mastering Python in 7 Days with Hands-On Exercises – Top Secret Coding Tips to Get an Unfair Advantage and Land Your Dream Job!


How to handle exceptions when working with JSON data in Python?

When working with JSON data in Python, you can handle exceptions using the try-except block. Here's the general approach:

  1. Import the necessary module: Start by importing the json module, which provides the necessary methods to work with JSON data.
1
import json


  1. Use a try-except block to handle exceptions: Wrap the code that may raise an exception in a try block, and then use an except block to handle the exception.
1
2
3
4
5
6
7
8
9
try:
    # Code that may raise an exception
    json_data = json.loads(json_string)
except json.JSONDecodeError as e:
    # Handle the JSONDecodeError exception
    print("Invalid JSON format:", str(e))
except Exception as e:
    # Handle any other exception
    print("An error occurred:", str(e))


  1. Handle specific exceptions: You can handle different types of exceptions separately. In the above example, we handle JSONDecodeError specifically to handle any issues with an invalid JSON format. You can also catch the more generic Exception to handle any other unexpected errors.
  2. Perform specific actions within exception handlers: Depending on your requirements, you can decide what actions to take within the exception handlers. It can be printing an error message, logging the error, or taking other relevant actions.


Note that it's essential to catch the specific JSON-related exceptions such as JSONDecodeError when working with JSON data to handle any potential issues during decoding or encoding processes.


What is JSON data?

JSON (JavaScript Object Notation) is a lightweight data interchange format. It is widely used in web services and APIs for transmitting data between a server and a client/application. JSON data is represented as key-value pairs, similar to a dictionary or an object in JavaScript.


JSON data is written in a simple and easy-to-read format, making it human-readable and machine-readable. It is mostly used for structured data, such as data from databases, configuration files, or complex data objects.


Example of JSON data:

1
2
3
4
5
{
  "name": "John Doe",
  "age": 30,
  "city": "New York"
}


In the example above, the JSON data represents a person's information with keys like "name", "age", and "city". The corresponding values are "John Doe", 30, and "New York", respectively.


How to print nested JSON data using Python?

You can use the json module in Python to load and parse the nested JSON data, and then use recursion to iterate through the nested structure and print the values.


Here's an example code that demonstrates how to do this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import json

# Example nested JSON data
data = {
    'name': 'John',
    'age': 30,
    'job': {
        'title': 'Engineer',
        'company': 'ABC Corp'
    },
    'address': {
        'street': '123 Street',
        'city': 'New York',
        'state': 'NY'
    }
}

# Function to print nested JSON data
def print_nested(data, indent=0):
    # Iterate through the dictionary items
    for key, value in data.items():
        # If the value is another dictionary, recursively call the function
        if isinstance(value, dict):
            print('\t' * indent + f'{key}:')
            print_nested(value, indent + 1)
        # Otherwise, print the key-value pair
        else:
            print('\t' * indent + f'{key}: {value}')

# Load and parse JSON data
json_data = json.loads(json.dumps(data))

# Call the function to print the nested JSON data
print_nested(json_data)


This will output:

1
2
3
4
5
6
7
8
9
name: John
age: 30
job:
    title: Engineer
    company: ABC Corp
address:
    street: 123 Street
    city: New York
    state: NY


Note that the print_nested function uses an indentation parameter to control the spacing of the nested levels. This is purely for formatting purposes and can be adjusted to your preference.


What is the json.dumps() function in Python?

The json.dumps() function is a built-in function in Python's json module. It is used to convert a Python object (such as a dictionary or a list) into a JSON formatted string. This function takes an object as input and returns a string representing that object in JSON format. It can also accept additional parameters such as indent and separators for custom formatting and control over the separators used in the output.


How to extract specific data from nested JSON in Python?

To extract specific data from nested JSON in Python, you can use the json module to load the JSON data into a Python dictionary, then apply appropriate indexing and slicing operations to access the desired data. Here's an example:


Let's say you have the following nested JSON data:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
nested_json = {
    "employees": [
        {
            "id": 1,
            "name": "John",
            "department": "IT"
        },
        {
            "id": 2,
            "name": "Jane",
            "department": "HR"
        }
    ]
}


To extract the name and department of each employee, you can do the following:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import json

# Load JSON data into a dictionary
data = json.loads(nested_json)

# Extract the name and department of each employee
for employee in data["employees"]:
    name = employee["name"]
    department = employee["department"]
    print(f"Name: {name}, Department: {department}")


Output:

1
2
Name: John, Department: IT
Name: Jane, Department: HR


This code iterates over the employees list and retrieves the name and department values for each employee using indexing syntax (data["employees"]) and accessing nested values (employee["name"] and employee["department"]).


How to pretty print JSON data in Python?

To pretty print JSON data in Python, you can use the json module along with the json.loads() function to parse the JSON data into a Python object, and then json.dumps() function with the indent parameter to format the data with indentation.


Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import json

json_data = '{"name": "John Doe", "age": 30, "city": "New York"}'

# Parse JSON data into a Python object
data = json.loads(json_data)

# Pretty print the data
pretty_data = json.dumps(data, indent=4)
print(pretty_data)


Output:

1
2
3
4
5
{
    "name": "John Doe",
    "age": 30,
    "city": "New York"
}


You can also use the sort_keys parameter of json.dumps() to sort the keys in alphabetic order:

1
2
pretty_data = json.dumps(data, indent=4, sort_keys=True)
print(pretty_data)


Output:

1
2
3
4
5
{
    "age": 30,
    "city": "New York",
    "name": "John Doe"
}


Facebook Twitter LinkedIn Whatsapp Pocket

Related Posts:

In Python, you can print even numbers by using loops and conditional statements. Here's an example code that prints even numbers from 1 to a given limit: # Define the limit limit = 20 # Iterate through numbers from 1 to limit for num in range(1, limit+1):...
In C++, you can initialize a nested struct by following these steps:Declare the outer struct and its members: Start by declaring the outer struct and its members. Each member can be of a different data type, including another struct. struct InnerStruct { i...
Python is increasingly becoming the go-to programming language for data analysts due to its extensive libraries and powerful data manipulation capabilities. When it comes to the amount of Python required for a data analyst, it varies depending on the specific ...