How to Turn a Python Dictionary into JSON Text with json.dumps
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
import json
<text> = json.dumps(<data>)
<text> = json.dumps(<data>, indent=<spaces>)
| Part | What 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
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))

Step 2: Run It
uv run python to_json_text.py
{"player": "Ada", "points": 42, "finished": true}
str
{
"player": "Ada",
"points": 42,
"finished": true
}

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
| Mistake | What happens | Do 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 file | It returns text and writes nothing | Use json.dump(data, file) for a file |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Object of type ... is not JSON serializable | A value JSON has no type for, such as a set | Convert 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
- json.dumps — every argument.
- Python-to-JSON conversion table — what each Python type becomes.
