๐Ÿ“„json.dumps, json.loads, JSONEncoder, JSONDecoderLESSON

JSON in Python

JSON (JavaScript Object Notation) is the universal data exchange format for web APIs and configuration files. Python's built-in json module handles serialization (Python โ†’ JSON string) and deserialization (JSON string โ†’ Python) with no extra dependencies.

Basic Serialization: json.dumps

json.dumps converts a Python object to a JSON string:

Python โ†” JSON Type Mapping

PythonJSON
dictobject {}
list, tuplearray []
strstring
int, floatnumber
Truetrue
Falsefalse
Nonenull

Basic Deserialization: json.loads

json.loads parses a JSON string back into Python objects:

File I/O: json.dump and json.load

For reading and writing JSON files, use json.dump and json.load (no 's') which work with file objects:

Handling Non-Serializable Types

By default, json.dumps raises TypeError for types it doesn't know about:

The default Parameter

Pass a function that converts unknown types to serializable ones:

Custom JSONEncoder Subclass

For reusable encoding logic, subclass json.JSONEncoder:

Custom Decoding with object_hook

object_hook is called on every JSON object (dict) during parsing, letting you convert dicts back to custom types:

Common Pitfalls

NaN and Infinity

Python's float('nan') and float('inf') are not valid JSON, but Python's json module serializes them by default (as NaN and Infinity). Many JSON parsers reject these:

Datetime Is Not Serializable

Always handle datetime explicitly:

Integer Keys Become Strings

JSON only supports string keys. Dict keys that are integers get silently converted:

Knowledge Check

What is the difference between `json.dumps` and `json.dump`?

What does the `object_hook` parameter in `json.loads` do?

What happens when you call `json.dumps({1: 'one', 2: 'two'})`?