Skip to main content

How to Turn a Python Dictionary into JSON Text with json.dumps

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

json.dumps turns a Python dictionary into JSON text: a string you can save, send over the network or print. The s stands for string, and that's how it differs from json.dump, which writes to a file. This guide turns a small dictionary into JSON on Python 3.15.2.

Syntax​

Syntax
import json

<text> = json.dumps(<data>)
<text> = json.dumps(<data>, indent=<spaces>)
PartWhat it means
<data>A dictionary, list, string, number, True, False or None, or a mix of them
indent=<spaces>Optional. Puts each item on its own line, indented by that many spaces
<text>The result: a str

The json reference says dumps will "Serialize obj to a JSON formatted str using this conversion table."

The Example​

A game score holds a player's name, their points and whether they finished. The script turns it into JSON twice: on one line, and indented.

Prerequisites​

  • uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

to_json_text.py
import json

score = {"player": "Ada", "points": 42, "finished": True}

text = json.dumps(score)
print(text)
print(type(text).__name__)
print(json.dumps(score, indent=2))

The to_json_text.py script in a macOS-style code window: a score dictionary, text = json.dumps(score), then prints of the text, its type and json.dumps(score, indent=2).

Step 2: Run It​

Terminal
uv run python to_json_text.py
Output
{"player": "Ada", "points": 42, "finished": true}
str
{
"player": "Ada",
"points": 42,
"finished": true
}

The terminal after uv run python to_json_text.py: the JSON on one line, then str, then the same JSON indented with one key per line.

The result is a str. Python's True became JSON's true, and every key has double quotes. With indent=2, each key went on its own line. The command works unchanged in PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
A set in the data: {"tags": {"fast", "red"}}TypeError: Object of type set is not JSON serializable, followed by when serializing dict item 'tags'Turn it into a list first: list(tags)
Using dumps to write a fileIt returns text and writes nothingUse json.dump(data, file) for a file

Troubleshooting​

SymptomLikely causeFix
Object of type ... is not JSON serializableA value JSON has no type for, such as a setConvert it to a list, string or number

FAQ​

What's the difference between dumps and dump?​

dumps returns the JSON as a string; dump writes it into a file you've opened. The reference says the arguments of dumps "have the same meaning as in dump()".

How do I make it readable?​

With indent, as in the second print.

Conclusion​

json.dumps(score) returned the dictionary as JSON text on one line, and indent=2 laid it out one key per line. Convert sets and other unsupported values before calling it.

Additional Resources​