Skip to content

Module 15 · Python Standard Libraries — topic 8 of 13

json

The json module in depth: compact and pretty output, sorting keys, ensure_ascii, separators, serialising custom types with default=, decoding with object_hook, and error handling.

Beginner 10 min read·Lesson 229 of 306 in Python Programming

Learning objectives

  • Control JSON output formatting
  • Serialise custom types with default
  • Rebuild custom types with object_hook

Definition

json encodes Python objects as JSON text (dumps/dump) and decodes JSON text into Python objects (loads/load). Hooks let you extend it to types JSON doesn't support natively, such as dates and sets.

Introduction

Basic JSON saving is one line, but real data includes dates, sets and custom classes. The json module's options and hooks handle them cleanly.

Why it matters

APIs and configuration files demand precise JSON. Knowing the options lets you produce exactly the format other systems expect.

Detailed explanation

dumps(obj) returns compact JSON; indent=2 pretty-prints; sort_keys=True orders keys for stable output.

separators=(",", ":") removes spaces for the smallest output; the default is (", ", ": ").

ensure_ascii=True (the default) escapes non-ASCII characters as \uXXXX; ensure_ascii=False keeps them readable.

Unsupported objects raise TypeError. The default= function is called for each such object and must return something serialisable (or raise TypeError).

loads(text, object_hook=func) calls func on every decoded dictionary, letting you convert values back into richer types.

dataclasses.asdict converts a dataclass to a dictionary, a convenient first step before dumping.

Invalid JSON raises json.JSONDecodeError with msg, lineno and colno.

JSON numbers have no separate integer and decimal types in the standard, but Python keeps the distinction: 3 loads as int and 3.0 as float. Use parse_float=decimal.Decimal when exact decimal values such as prices matter.

Syntax

Python
import json
json.dumps(data, indent=2, sort_keys=True, ensure_ascii=False)
json.dumps(data, default=encode)
json.loads(text, object_hook=decode)
  • Options control formatting.
  • default= serialises custom types.
  • object_hook rebuilds them.

Code examples

Formatting options

Python
import json
data = {"b": 2, "a": [1, 2], "ok": None}
print(json.dumps(data))
print(json.dumps(data, sort_keys=True, separators=(",", ":")))
print(json.dumps("नमस्ते"), json.dumps("नमस्ते", ensure_ascii=False))
Output
{"b": 2, "a": [1, 2], "ok": null}
{"a":[1,2],"b":2,"ok":null}
"\u0928\u092e\u0938\u094d\u0924\u0947" "नमस्ते"

Pretty-printing

Python
import json
print(json.dumps({"name": "Asha", "skills": ["py", "sql"]}, indent=2))
Output
{
  "name": "Asha",
  "skills": [
    "py",
    "sql"
  ]
}

More examples

Dates and sets round trip

Python
import json
from dataclasses import asdict, dataclass
from datetime import date
@dataclass
class Task:
title: str
due: date
tags: set
def encode(obj):
if isinstance(obj, date):
return obj.isoformat()
if isinstance(obj, set):
return sorted(obj)
raise TypeError(f"cannot serialise {type(obj).__name__}")
def decode(d):
if "due" in d:
d["due"] = date.fromisoformat(d["due"])
return d
tasks = [Task("report", date(2026, 12, 1), {"work", "urgent"})]
text = json.dumps([asdict(t) for t in tasks], default=encode)
print(text)
loaded = json.loads(text, object_hook=decode)
print(loaded[0]["due"].strftime("%d %b"), type(loaded[0]["due"]).__name__)
try:
json.dumps({"x": object()}, default=encode)
except TypeError as e:
print(e)
Output
[{"title": "report", "due": "2026-12-01", "tags": ["urgent", "work"]}]
01 Dec date
cannot serialise object

Step-by-step explanation

  • encode turns dates into ISO strings and sets into sorted lists; anything else is rejected with a clear TypeError.
  • decode runs for every dictionary while loading and turns the due string back into a date.
  • The round trip keeps the data's meaning even though JSON has no date type.

Expected output

Running “Dates and sets round trip” prints exactly:

TextOutput
[{"title": "report", "due": "2026-12-01", "tags": ["urgent", "work"]}]
01 Dec date
cannot serialise object

Practical applications

  • APIs exchanging timestamps as ISO strings.
  • Saving application state that contains custom objects.

Best practices

  • Use ISO strings for dates.
  • Raise TypeError in default for unknown types.
  • Use sort_keys for stable, diff-friendly files.

Common mistakes

Returning None from default

Avoid

def encode(obj):
if isinstance(obj, date):
return obj.isoformat()

Prefer

def encode(obj):
if isinstance(obj, date):
return obj.isoformat()
raise TypeError(type(obj).__name__)

Returning None silently writes null for unknown objects.

Important notes

  • json.JSONEncoder can be subclassed as an alternative to default=.

Key takeaways

  • indent, sort_keys, separators and ensure_ascii control output.
  • default= encodes custom types.
  • object_hook decodes them.

Try it yourself

  1. 1
    Serialise a list of Decimal prices as strings and load them back as Decimal.
  2. 2
    Produce minified and pretty versions of the same JSON and compare their sizes.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic