liveBook · Manning

Json.dumps()

As explained in Python How-To

dumps is a json module function that serializes a Python object to a JSON-formatted string.

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.
CH09_F05_Cui

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

How Python How-To covers it

How deep it goes
Defines built-in conversions, demonstrates formatting options, and explains custom-class fallback without detailing encoder internals.
Examples
Uses mixed built-in values, formatted dictionaries, sorted keys, and a Task instance converted through __dict__.
What it assumes
Assumes basic Python objects and JSON familiarity while distinguishing serialization from deserialization.
What you can do after
Apply it via Python's json module to serialize built-ins, format output, and provide fallback handling for custom objects.
How it connects
Connects serialization with deserialization, JSON strings, JSON files, custom classes, and pickle.

Also explained in

Compare how 2 books explain json.dumps() →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.