liveBook · Manning

Json.dumps()

As explained in The Quick Python Book, Fourth Edition

json.dumps() is a Python function that serializes a Python value as a JSON-formatted string.

json.dumps() serializes a Python value as one JSON-formatted string. Its file-writing counterpart, json.dump(), writes that string to an object with a write() method. section 22.3.1

Use json.dumps() when you need to:

  • Convert a Python object, such as a weather report dictionary, into JSON text. section 22.3.1
  • Improve readability with the indent parameter, for example json.dumps(weather, indent=2). section 22.3.1
  • Keep multiple records as one valid JSON object by placing them in a list or enclosing structure before serialization. section 22.3.1

Serialize a weather report

json_text = json.dumps(weather) print(json_text) This returns one JSON string. By contrast, json.dump(weather, outfile) writes the serialized content directly to outfile. section 22.3.1

print(json.dumps(weather, indent=2))
 
{
  "latitude": 41.879482,
  "longitude": -87.64975,
  "generationtime_ms": 0.025987625122070312,
  "utc_offset_seconds": 0,
  "timezone": "GMT",
  "timezone_abbreviation": "GMT",
  "elevation": 185.0,
  "current_units": {
    "time": "iso8601",
    "interval": "seconds",
    "temperature_2m": "\u00b0C",
    "wind_speed_10m": "km/h"
  },
  "current": {
    "time": "2024-09-02T02:15",
    "interval": 900,
    "temperature_2m": 16.9,
    "wind_speed_10m": 13.8
  }
}

Inspect the same weather object as indented JSON, including nested objects and escaped characters. section 22.3.1

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains return behavior, indentation, file contrast, and repeated-object validity without detailing customization options.
Examples
Uses a weather report dictionary, an indented output listing, and lists or structures containing multiple reports.
What it assumes
Assumes familiarity with Python objects, files, and JSON while relating JSON values to dictionaries, lists, strings, numbers, booleans, and None.
What you can do after
Apply json.dumps() to produce compact or indented JSON text and choose json.dump() for direct file output.
How it connects
Connects JSON serialization with json.dump(), json.loads(), json.load(), Python objects, and the requests library.

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 The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.