Convert a Nested Dictionary to JSON in Python

While working on a project where I had to send structured data from a Python backend to a web application. The data was stored in a nested dictionary, and I needed to convert it into JSON format.

The issue is… while converting a simple dictionary to JSON is easy, many people get confused when the dictionary has multiple nested levels.

In this tutorial, I’ll show you exactly how I handle this in my projects. I’ll cover different methods, share code examples, and explain each step in a simple way. By the end, you’ll be able to confidently convert any nested dictionary into JSON.

What is JSON and Why Do We Need It?

JSON (JavaScript Object Notation) is a lightweight format for storing and exchanging data. It’s widely used in APIs, web apps, and databases.

In Python, we often use JSON when:

A nested dictionary in Python looks very similar to JSON. But before sending or saving it, we must explicitly convert it into JSON format.

Method 1 – Convert Nested Dictionary to JSON Using json.dumps()

The most common way to convert a dictionary (including nested ones) into JSON is by using the json module’s dumps() function in Python.

Here’s how I usually do it:

import json

# Example nested dictionary (using US-based data)
employee_data = {
    "company": "TechCorp USA",
    "employees": {
        "101": {
            "name": "John Smith",
            "department": "Finance",
            "location": "New York"
        },
        "102": {
            "name": "Emily Johnson",
            "department": "Engineering",
            "location": "San Francisco"
        }
    }
}

# Convert dictionary to JSON string
json_data = json.dumps(employee_data, indent=4)

print(json_data)

You can see the output in the screenshot below.

python dict to json

Explanation:

  • I imported the built-in json module.
  • Used json.dumps() to convert the dictionary into a JSON string.
  • Added indent=4 to make the output more readable.

This is the method I use most often when I just need a quick and clean conversion.

Method 2 – Save Nested Dictionary as a JSON File

Sometimes, instead of just printing JSON, I need to save it into a .json file. For example, when storing user data or exporting reports.

Here’s how I do it:

import json

# Nested dictionary with US state data
state_population = {
    "California": {"population": 39538223, "capital": "Sacramento"},
    "Texas": {"population": 29145505, "capital": "Austin"},
    "Florida": {"population": 21538187, "capital": "Tallahassee"}
}

# Save dictionary to a JSON file
with open("state_population.json", "w") as file:
    json.dump(state_population, file, indent=4)

print("JSON file created successfully!")

You can see the output in the screenshot below.

python dictionary to json

This method is great when I want to keep a permanent record of my nested dictionary in JSON format.

Method 3 – Sort Keys While Converting

In some projects, I need the JSON output to always have keys in alphabetical order. This makes it easier to compare JSON files or debug.

import json

nested_dict = {
    "zebra": {"count": 5, "location": "San Diego Zoo"},
    "lion": {"count": 3, "location": "Bronx Zoo"},
    "elephant": {"count": 2, "location": "Smithsonian Zoo"}
}

# Convert with sorted keys
json_data = json.dumps(nested_dict, indent=4, sort_keys=True)

print(json_data)

You can see the output in the screenshot below.

dictionary to json python

Notice how the keys (elephant, lion, zebra) are now sorted alphabetically.

Method 4 – Handle Non-Serializable Data

Sometimes, a dictionary contains objects (like datetime) that JSON doesn’t support directly. In those cases, I use a custom function.

import json
from datetime import datetime

# Nested dictionary with datetime
event_data = {
    "event": "Python Conference",
    "details": {
        "location": "Chicago",
        "date": datetime(2025, 5, 20, 10, 0)
    }
}

# Custom serializer
def custom_serializer(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()
    raise TypeError("Type not serializable")

# Convert with custom function
json_data = json.dumps(event_data, indent=4, default=custom_serializer)

print(json_data)

You can see the output in the screenshot below.

dict to json python

This way, I can handle special data types without breaking the JSON conversion.

Method 5 – Convert JSON Back to Dictionary

It’s also common to convert JSON back into a Python dictionary. I use json.loads() for that.

import json

# JSON string
json_string = '{"city": "Boston", "temperature": {"morning": 65, "afternoon": 75}}'

# Convert JSON back to dictionary
dict_data = json.loads(json_string)

print(dict_data["temperature"]["afternoon"])

This is very useful when working with APIs that return JSON responses.

While there’s no shortage of ways to work with JSON in Python, these are the methods I use most often in real-world projects.

  • json.dumps() for quick conversions
  • json.dump() for saving to files
  • sort_keys=True for consistent outputs
  • Custom serializers for complex objects

Once you understand these techniques, converting nested dictionaries to JSON becomes second nature.

You may also read other Python articles:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.