|
| Home |
|---|
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.
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.
json.dumps(dictionary)
import json
student = {
"name":"Alice",
"age":21,
"course":"Python"
}
result = json.dumps(student)
print(result)
print(type(result))
{"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.
The indent parameter adds line breaks and spacing, making the JSON output far easier to read — especially for larger or nested dictionaries.
import json
student = {
"name":"Alice",
"age":21,
"course":"Python"
}
result = json.dumps(student, indent=4)
print(result)
{
"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.
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.
import json
student = {
"course":"Python",
"name":"Alice",
"age":21
}
result = json.dumps(student, indent=4, sort_keys=True)
print(result)
{
"age": 21,
"course": "Python",
"name": "Alice"
}
Even though course was defined first in the dictionary, sort_keys=True reorders the output alphabetically by key.
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.
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.
When file size matters more than readability, such as sending JSON over a network, use the separators parameter to remove the default spacing.
import json
student = {"name":"Alice","age":21,"course":"Python"}
result = json.dumps(student, separators=(",", ":"))
print(result)
{"name":"Alice","age":21,"course":"Python"}
separators=(",", ":") removes the spaces that normally follow commas and colons, producing the smallest possible valid JSON string.
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.
import json
from datetime import date
student = {
"name":"Alice",
"enrolled":date(2024, 1, 15)
}
result = json.dumps(student, default=str)
print(result)
{"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.
json.dumps() handles nested dictionaries and lists automatically, with no extra code required.
import json
student = {
"name":"Alice",
"grades":{"math":90,"science":85},
"hobbies":["reading","chess"]
}
result = json.dumps(student, indent=4)
print(result)
{
"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.
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.
json.dumps(dictionary)json.dump(dictionary, file)indent=4sort_keys=Trueseparators=(",", ":")default=str or a custom encoder functionjson module before using json.dumps().get() no longer work on the resultdict until json.dumps() or json.dump() is calledjson.dumps() on a dictionary with non-serializable values, like sets or custom objects, without a default handler, which raises a TypeErrorjson.dumps() and then manually writing the result to a file instead of using json.dump() directlysort_keys=True will reorder keys alphabetically
Import the json module and call json.dumps(dictionary). This returns a JSON-formatted string.
json.dumps() returns a JSON string in memory. json.dump() writes JSON directly to a file object, without returning a string.
Pass the indent argument, for example json.dumps(dictionary, indent=4), to format the output across multiple lines with indentation.
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.
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.
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.
Home Tutorial Online Live Trainings Contact Us © 2026 All rights reserved by www.PythonTutor.net