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

