json.dumps in Python

Turn a dict into JSON text, and teach it about dates, decimals and sets.

In Python, json.dumps turns a dict, a list or any other JSON-friendly value into a string of JSON. It lives in the standard library's json module.

The short answer

import json

data = {"name": "Nitro", "stars": 120, "tags": ["python", "static"], "archived": False, "licence": None}
text = json.dumps(data)

print(text)

The result is a str. True, False and None are written as true, false and null, and strings always get double quotes.

Python dict to JSON

A dict converts cleanly as long as it holds strings, numbers, booleans, None, lists, tuples and other dicts. Two conversions are worth knowing about before they surprise you:

json.dumps({1: "one", 2: "two"})    # '{"1": "one", "2": "two"}'
json.dumps({"point": (3, 4)})       # '{"point": [3, 4]}'

JSON keys are always strings, so integer keys are converted, and a tuple is written as an array. Neither comes back as it went in: after json.loads you have string keys and a list.

Keys keep the order of the dict. Pass sort_keys=True if you want them alphabetical.

dumps or dump?

json.dumps returns a string. json.dump, without the s, writes straight to an open file and returns nothing:

with open("data.json", "w", encoding="utf-8") as f:
    json.dump(data, f)

Both take the same keyword arguments. There is more in writing a JSON file.

indent and separators

The default output is one line with a space after each comma and colon. indent spreads it over several lines for people, and separators squeezes it for machines:

json.dumps({"name": "Nitro", "stars": 120}, indent=2)
# '{\n  "name": "Nitro",\n  "stars": 120\n}'

json.dumps(data, separators=(",", ":"))
# '{"name":"Nitro","stars":120,"tags":["python","static"],"archived":false,"licence":null}'

The pretty printing recipe goes through indent, sort_keys and ensure_ascii in detail.

Object of type X is not JSON serializable

JSON has no dates, no decimals and no sets, so json.dumps refuses them:

from datetime import datetime
from decimal import Decimal

order = {
    "placed": datetime(2026, 1, 5, 9, 30),
    "total": Decimal("19.99"),
    "tags": {"gift", "fragile"},
}

try:
    json.dumps(order)
except TypeError as e:
    print(e)  # Object of type datetime is not JSON serializable

The fix is the default argument: a function that json.dumps calls for every value it does not know how to write. Return something it does know, or raise TypeError for anything you did not expect.

def encode(value):
    if isinstance(value, datetime):
        return value.isoformat()
    if isinstance(value, Decimal):
        return str(value)
    if isinstance(value, set):
        return sorted(value)
    raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable")


json.dumps(order, default=encode)
# '{"placed": "2026-01-05T09:30:00", "total": "19.99", "tags": ["fragile", "gift"]}'

You decide what each type turns into. Writing a Decimal as a string keeps every digit, where float(value) would give a JSON number and the usual rounding. Sorting the set makes the output the same on every run.

default=str is the quick version. It is fine for logs, but look at what it does to the set:

print(json.dumps(order, default=str))
# {"placed": "2026-01-05 09:30:00", "total": "19.99", "tags": "{'fragile', 'gift'}"}

The set has become one string of Python syntax, in whatever order the set happened to be in, and nothing reading the JSON can turn it back into a list.

Keys are stricter than values. A tuple used as a key fails with keys must be str, int, float, bool or None, not tuple, and default is not consulted. Rebuild the dict with string keys first.

Non-ASCII text and NaN

Accented characters are escaped unless you ask otherwise:

json.dumps({"city": "Zürich"})                       # '{"city": "Z\\u00fcrich"}'
json.dumps({"city": "Zürich"}, ensure_ascii=False)   # '{"city": "Zürich"}'

float("nan") and infinity are written as NaN and Infinity, which Python reads back but strict parsers in other languages reject. Pass allow_nan=False to get a ValueError instead of invalid output.

The shorter way with Nitro DataStore

Nitro DataStore does not replace json.dumps. Where it helps is building the nested dict you are about to serialise, because set creates the levels in between for you:

from nitro_datastore import NitroDataStore

config = NitroDataStore({"site": {"name": "Nitro"}})
config.set("site.theme.color", "#ffc700")
config.set("cache.ttl", 3600)

json.dumps(config.to_dict())
# '{"site": {"name": "Nitro", "theme": {"color": "#ffc700"}}, "cache": {"ttl": 3600}}'

Note the to_dict(). Passing the store itself to json.dumps raises the same "not JSON serializable" error as any other custom object. If your data is already a dict, this adds nothing, and json.dumps(data) is the whole job.

Common questions

Does json.dumps return bytes? No, it returns a str. Call .encode("utf-8") on the result if you need bytes for a socket or an HTTP body.

How do I serialise my own class? Convert it to a dict first. For a dataclass that is json.dumps(dataclasses.asdict(obj)). For anything else, handle it in your default function.

How do I turn the JSON back into a dict? With json.loads, covered in parsing JSON.

This page uses Nitro DataStore.

Read JSON with dot notation and a chainable query builder. No schema to define, no ORM to learn.

$ pip install nitro-datastore