# JSON Serialization & Parsing (dumps, loads)

> Bridge Python data structures and JSON strings: serializing dicts and lists with json.dumps(), parsing JSON with json.loads(), mapping Python types (None, True, tuples), and solving serialization errors with custom encoders.

Subject: Python | Lesson 20 of 24 | 7 min read
Interactive lesson: https://codewithanimation.in/python/json
Previous: [File I/O & Context Managers (with open)](https://codewithanimation.in/python/file-io.md) | Next: [Exception Handling: try, except, else, finally](https://codewithanimation.in/python/exceptions.md)

## The json Module: Strings vs Streams

JSON (JavaScript Object Notation) is the universal format for web APIs, configuration files, and cross-language data exchange. Python's standard library `json` module provides four primary functions differentiated by an 's' suffix.

Functions ending in 's' operate on strings: `json.dumps(obj)` serializes a Python object into a JSON string in memory, and `json.loads(str)` deserializes a JSON string back into native Python types.

Functions without 's' operate directly on file streams: `json.dump(obj, file_obj)` writes JSON directly into an open file, and `json.load(file_obj)` reads and parses JSON from an open file stream.

## Python vs JSON Type Mappings

JSON syntax and Python syntax are similar but not identical. The `json` module performs automatic two-way translation between them.

Python dictionaries map to JSON objects `{}`; Python lists and tuples map to JSON arrays `[]`.

Crucially, boolean literals map between capital and lowercase: Python `True` becomes JSON `true`, and `False` becomes `false`. Python's `None` singleton translates to JSON's `null`. Strings always serialize to double quotes `"` in valid JSON, even if defined using single quotes `'` in Python.

## Handling Dates, Sets, and Custom Encoders

The standard JSON specification only supports objects, arrays, strings, numbers, booleans, and null. Python structures like `set`, `datetime.date`, `Decimal`, and custom class instances cannot be serialized out-of-the-box.

When encountering an unsupported type, `json.dumps()` raises `TypeError: Object of type X is not JSON serializable`.

To resolve this, supply a custom conversion function to the `default` parameter of `json.dumps()`, e.g. `default=str` or `default=lambda o: list(o) if isinstance(o, set) else o.__dict__`.

## Common mistake: Single Quotes and Trailing Comma JSON Syntax Errors

A frequent beginner trap is attempting to parse Python-like dictionaries with single quotes using `json.loads("{'key': 'value'}")`. JSON syntax strictly mandates double quotes `"`. Passing single quotes raises `json.decoder.JSONDecodeError`.

Similarly, while Python allows trailing commas in dictionaries and lists, the official JSON specification strictly forbids them. Trying to parse `{"items": [1, 2, ]}` will fail with an unexpected token error.

## Tip: Format Debug Logs with indent=2 and sort_keys=True

When inspecting large API responses or debugging configurations, pass `indent=2` and `sort_keys=True` to `json.dumps()`. This renders human-readable pretty-printed JSON with consistent alphabetical key ordering.

## Try it: The JSON Translation Conveyor

Transform Python dictionaries into compliant JSON strings and vice-versa. Test what happens when serializing unsupported types like sets or datetimes, and see how the default parameter resolves serialization errors.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/python/json

## Check yourself

### Question 1

What does `json.loads('{"active": true, "user": null}')` return in Python?

- A. {'active': True, 'user': None}
- B. {'active': true, 'user': null}
- C. Raises JSONDecodeError because null is not valid Python
- D. A raw JSON string

Correct answer: A

The `json.loads` function translates JSON tokens into native Python values: `true` becomes `True`, and `null` becomes `None`.

- Why not B: Python parses lowercase true to True, and null to None.
- Why not C: null is valid JSON syntax that json.loads translates to Python None.
- Why not D: loads parses JSON strings into native Python dictionaries.

### Question 2

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

- A. json.dumps() returns a Python string; json.dump() writes directly to a file stream
- B. json.dumps() is for simple types; json.dump() is for complex classes
- C. json.dump() is deprecated and removed in Python 3
- D. json.dumps() parses JSON; json.dump() writes JSON

Correct answer: A

The 's' in `dumps` and `loads` stands for 'string'. `json.dump(obj, f)` writes JSON to an open file stream directly without creating an intermediate giant string in memory.

- Why not B: Both functions support the same serialization capabilities; the difference is output destination.
- Why not C: json.dump() is the standard way to write JSON directly into open files.
- Why not D: Both serialize Python to JSON; parsing is performed by loads and load.

### Question 3

Why does `json.dumps({'ids': {1, 2, 3}})` raise a `TypeError`?

- A. Sets are not natively supported in the official JSON specification
- B. Integer keys cannot be serialized
- C. The dictionary must have at least two keys
- D. Curly braces are illegal in Python dictionaries

Correct answer: A

The JSON standard only supports strings, numbers, booleans, null, arrays, and objects. Python sets have no direct JSON equivalent, so `json.dumps` raises a `TypeError` unless a custom `default` converter is supplied.

- Why not B: The integers here are values in a set, not dictionary keys.
- Why not C: Single-key dictionaries serialize without issue.
- Why not D: Curly braces are standard dictionary and set syntax in Python.

## Remember this

- dumps/loads operate on memory strings; dump/load operate directly on file streams.
- Python None maps to JSON null; True/False map to lowercase true/false.
- JSON strictly requires double quotes (") for strings and keys; single quotes trigger JSONDecodeError.
- Tuples serialize into JSON arrays, and deserialize back into Python lists.
- Pass a custom callable to default in json.dumps() to serialize sets, dates, and custom objects.
