json.dumps() serializes a Python object into a JSON-formatted string. It provides the outgoing counterpart to json.loads(): Python data becomes JSON data suitable for communication with other systems. section 9.3.4 section 9.3.5
For built-in values, json.dumps() performs the corresponding JSON conversions:
- Python strings use JSON double quotes; False becomes false; None becomes null. section 9.3.4
- Lists become JSON arrays, dictionaries become JSON objects, and numeric keys are converted to strings because JSON keys must be strings. section 9.3.4
- Use indent for readable multiline output and sort_keys=True for alphabetically ordered object keys. section 9.3.4
- Use dump() instead when processing a JSON file directly; dumps() handles a JSON string. section 9.3.5
Serializing built-in data
builtin_data = ['text', False, {"0": None, 1: [1.0, 2.0]}] print(json.dumps(builtin_data)) # ["text", false, {"0": null, "1": [1.0, 2.0]}] section 9.3.4
Handling a custom class
Custom class instances are not JSON-serializable by default. Provide default as a fallback encoder when the object needs custom serialization: json.dumps(task, default=lambda x: x.__dict__) # {"title": "Laundry", "desc": "Wash clothes", "urgency": 3} This approach explicitly chooses the instance attributes to serialize. section 9.3.4 section 9.3.5
Figure 9.5 Data conversion between JSON and Python. When you convert JSON to Python, the process is deserialization; when you convert Python to JSON, the process is serialization.
Use the conversion diagram to distinguish deserialization from serialization: JSON becomes Python in one direction, while Python becomes JSON in the other. section 9.3.4

