Skip to main content
St Louis

Back to all posts

How to Print Nested JSON Data Using Python?

Published on
6 min read
How to Print Nested JSON Data Using Python? image

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

  1. Import the required libraries:

import json

  1. Load the JSON data from a file or API response:

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:

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:

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.

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.

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.

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:

{ "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:

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:

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:

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:

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:

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:

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:

{ "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:

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

Output:

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