How to Convert a Python Dict to JSON

In my Python development journey, I have dealt with thousands of data conversions. One of the most common tasks I face is turning a Python dictionary into a JSON object.

I remember the first time I had to do this; I was trying to send some user data from a Django backend to a React frontend.

It seemed complicated at first, but Python makes this incredibly simple once you know which function to use.

In this tutorial, I will show you exactly how to convert a Python dict to JSON based on my firsthand experience.

Why You Need to Convert Dict to JSON

In most modern applications, we don’t just keep data inside our Python script. We often need to send that data to a web browser, a mobile app, or save it for later use.

Since JSON is the standard language of the web, converting your dictionaries is a skill you will use daily.

I use this constantly when I’m building APIs or saving configuration settings for my automation scripts.

Method 1: Convert a Dictionary to a JSON String

When you want to turn a dictionary into a string (perhaps to send it via an API), you use json.dumps().

I usually call this “dump-s” to remember it stands for “dump string.”

Here is how I do it using an example of a small business based in Chicago:

import json

# My dictionary containing USA business data
business_info = {
    "name": "Windy City Tech Solutions",
    "location": "Chicago, IL",
    "employees": 15,
    "is_active": True,
    "services": ["Cloud Migration", "Python Development", "Cyber Security"]
}

# Converting the dictionary to a JSON string
json_string = json.dumps(business_info)

# Outputting the result
print(json_string)
print(type(json_string))

You can see the output in the screenshot below.

Convert a Python Dict to JSON

In the example above, you’ll notice that the Python True was converted to a lowercase true. This is exactly what we want, as JSON follows different syntax rules than Python.

Method 2: Write a Dictionary Directly to a JSON File

Sometimes I don’t need a string; I just want to save the data to a file on my hard drive. For this, I use json.dump(). Note that there is no “s” at the end here.

I frequently use this for saving user preferences in my desktop applications.

import json

# Employee data for a New York office
employee_data = {
    "id": 1024,
    "name": "Sarah Jenkins",
    "department": "Marketing",
    "office": "New York City, NY",
    "remote": False
}

# Writing the dictionary to a file named 'data.json'
with open('employee_record.json', 'w') as json_file:
    json.dump(employee_data, json_file)

print("Data successfully saved to employee_record.json")

You can see the output in the screenshot below.

How to Convert a Python Dict to JSON

Using the with statement is a habit I’ve formed over the years. It ensures the file is closed properly even if something goes wrong during the writing process.

Method 3: Make the JSON Pretty (Indentation)

When I’m debugging or creating a configuration file for a client, I hate looking at a single line of text.

Standard JSON output is “minified,” which means it has no spaces or newlines.

To make it readable for humans, I use the indent parameter.

import json

# Real estate listing in Austin, Texas
listing = {
    "address": "123 Longhorn Way",
    "city": "Austin",
    "state": "TX",
    "price": 450000,
    "features": {"beds": 3, "baths": 2, "sqft": 1800}
}

# Pretty-printing the JSON with 4 spaces of indentation
pretty_json = json.dumps(listing, indent=4)

print(pretty_json)

You can see the output in the screenshot below.

Convert Python Dict to JSON

Adding an indent=4 makes the data look professional and easy to scan at a glance.

Method 4: Sort the Keys Alphabetically

There are times when I need my JSON files to be consistent, especially when I’m using version control like Git.

If the keys move around, Git will show a “change” even if the data is the same.

I solve this by using the sort_keys parameter.

import json

# Travel itinerary for a trip to Yellowstone
trip = {
    "destination": "Yellowstone National Park",
    "state": "Wyoming",
    "duration_days": 7,
    "transportation": "SUV Rental"
}

# Sorting keys alphabetically
sorted_json = json.dumps(trip, indent=4, sort_keys=True)

print(sorted_json)

Now, the keys will always appear in the same order (duration_days, destination, state, transportation).

Common Issues to Watch Out For

In my experience, the biggest mistake beginners make is trying to serialize things that aren’t “JSON-ready.”

For example, a Python datetime object or a custom class cannot be converted using json.dumps() directly.

If you try, you will see a TypeError.

To fix this, I usually convert those specific objects into strings or integers before dumping them.

Another small detail is the ensure_ascii parameter.

If your data contains emojis or non-English characters, you might want to set ensure_ascii=False to keep them as they are.

Converting a Python dictionary to JSON is a fundamental task for any developer.

Whether you are saving a file or sending data to an API, these methods will cover 99% of your needs.

You may also read:

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.