Python Tutoring Online
 Home

Python Convert Dictionary to JSON

To convert a Python dictionary to JSON, use the built-in json module's json.dumps() function, which turns a dictionary into a JSON-formatted string that web APIs, config files, and other programs can read.

In this tutorial you will learn how to convert a dictionary to JSON, format the output for readability, sort keys alphabetically, save JSON directly to a file, handle values that aren't JSON-serializable by default, and the mistakes beginners make most often.

Need Help Learning Python?

Working with JSON is a common requirement in Python programming. Beginners often encounter JSON when working with web applications or APIs.

Understanding how to convert dictionaries to JSON helps when exchanging data between programs.

Get Python Tutoring Help

Convert Dictionary to JSON Using json.dumps()

The json.dumps() function converts a Python dictionary into a JSON-formatted string. It's part of Python's built-in json module, so no extra installation is needed — just import json.

Syntax

Python
json.dumps(dictionary)

Example

Python
import json

student = {
"name":"Alice",
"age":21,
"course":"Python"
}

result = json.dumps(student)

print(result)
print(type(result))

Output


{"name": "Alice", "age": 21, "course": "Python"}
<class 'str'>

JSON format always uses double quotes around keys and string values, which is why the output looks slightly different from printing the dictionary directly. type(result) confirms the output is a str, ready to be sent over a network or written to a file.

Convert Dictionary to Formatted (Pretty-Printed) JSON

The indent parameter adds line breaks and spacing, making the JSON output far easier to read — especially for larger or nested dictionaries.

Python
import json

student = {
"name":"Alice",
"age":21,
"course":"Python"
}

result = json.dumps(student, indent=4)

print(result)

Output


{
    "name": "Alice",
    "age": 21,
    "course": "Python"
}

indent=4 formats each key-value pair on its own line with four-space indentation. The data itself doesn't change — only how it's displayed.

Sort Keys Alphabetically in JSON Output

By default, json.dumps() preserves the dictionary's original key order. Set sort_keys=True to output keys alphabetically instead — useful for consistent, predictable output, such as when comparing JSON snapshots or writing tests.

Python
import json

student = {
"course":"Python",
"name":"Alice",
"age":21
}

result = json.dumps(student, indent=4, sort_keys=True)

print(result)

Output


{
    "age": 21,
    "course": "Python",
    "name": "Alice"
}

Even though course was defined first in the dictionary, sort_keys=True reorders the output alphabetically by key.

Save a Dictionary as a JSON File

To write a dictionary directly to a .json file instead of getting a string back, use json.dump() (without the "s") together with an open file object.

Python
import json

student = {
"name":"Alice",
"age":21,
"course":"Python"
}

with open("student.json", "w") as file:
    json.dump(student, file, indent=4)

json.dump() writes the JSON output straight into the file, so there's no need to call json.dumps() first and then write the string separately. This is the standard way to save configuration data or program output to disk.

Compact JSON Output Using separators

When file size matters more than readability, such as sending JSON over a network, use the separators parameter to remove the default spacing.

Python
import json

student = {"name":"Alice","age":21,"course":"Python"}

result = json.dumps(student, separators=(",", ":"))

print(result)

Output


{"name":"Alice","age":21,"course":"Python"}

separators=(",", ":") removes the spaces that normally follow commas and colons, producing the smallest possible valid JSON string.

Handling Values That Aren't JSON-Serializable

json.dumps() only understands basic Python types — strings, numbers, booleans, lists, dictionaries, and None. Values like dates, sets, or custom objects raise a TypeError unless you tell json.dumps() how to convert them.

Python
import json
from datetime import date

student = {
"name":"Alice",
"enrolled":date(2024, 1, 15)
}

result = json.dumps(student, default=str)

print(result)

Output


{"name": "Alice", "enrolled": "2024-01-15"}

The default=str argument tells json.dumps() to fall back to calling str() on any value it can't serialize directly, converting the date object into a plain string instead of raising an error.

Convert Nested Dictionaries to JSON

json.dumps() handles nested dictionaries and lists automatically, with no extra code required.

Python
import json

student = {
"name":"Alice",
"grades":{"math":90,"science":85},
"hobbies":["reading","chess"]
}

result = json.dumps(student, indent=4)

print(result)

Output


{
    "name": "Alice",
    "grades": {
        "math": 90,
        "science": 85
    },
    "hobbies": [
        "reading",
        "chess"
    ]
}

Both the nested dictionary and the list are converted correctly, with the indent parameter formatting each nesting level with additional spacing.

Why Convert a Dictionary to JSON

JSON is the standard format for exchanging data between web applications, APIs, and services written in different programming languages. Converting a dictionary to JSON makes it possible to send structured Python data over HTTP, store configuration or application state in a portable file, and log structured data in a format other tools can parse. Unlike str(dictionary), JSON output follows a strict, well-defined specification that other systems can reliably read back.

Which Option Should You Use?

Common Beginner Mistakes

Frequently Asked Questions

How do I convert a Python dictionary to JSON?

Import the json module and call json.dumps(dictionary). This returns a JSON-formatted string.

What is the difference between json.dumps() and json.dump()?

json.dumps() returns a JSON string in memory. json.dump() writes JSON directly to a file object, without returning a string.

How do I make JSON output readable?

Pass the indent argument, for example json.dumps(dictionary, indent=4), to format the output across multiple lines with indentation.

Why does json.dumps() raise a TypeError?

This happens when the dictionary contains a value json.dumps() doesn't know how to serialize, such as a date, set, or custom object. Use the default parameter, for example default=str, to handle these values.

How do I save a Python dictionary as a JSON file?

Open a file in write mode and use json.dump(dictionary, file) to write the JSON output directly into it, instead of converting to a string first.

Related Python Dictionary Tutorials


Stuck Learning Python?

Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.

Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.

  • Fix your Python code
  • Get help with assignments
  • Real World Python Projects

Get Python Tutoring Help



Stuck Learning Python?

Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.

Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.

    Get Python Tutoring

PythonTutor.net

Home    Tutorial     Online Live Trainings    Contact Us           © 2026 All rights reserved by www.PythonTutor.net