liveBook · Manning

Json.dump()

As explained in The Quick Python Book, Fourth Edition

json.dump() is a Python function that serializes a Python value as JSON and writes it to a file-like object.

json.dump() serializes a Python value as JSON and writes the resulting string to a file-like object with a write() method. section 22.3.1

Write a weather report

outfile = open("weather_01.json", "w") json.dump(weather, outfile) outfile.close() Unlike json.dumps(weather), which returns the serialized string, json.dump() writes it directly to outfile.

Use the related options and functions deliberately:

  • Use json.dumps() when the serialized JSON should remain a string instead of being written to a file. section 22.3.1
  • Do not repeatedly dump separate objects into one file and expect json.load() to parse the whole file; store them in a list or enclosing object instead. section 22.3.1

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains the file-like destination, formatting option, dump-versus-dumps distinction, and repeated-object limitation.
Examples
Demonstrates saving a weather dictionary, pretty-printing JSON, and grouping multiple weather reports under one object.
What it assumes
Assumes Python values, file objects, and basic JSON parsing while contrasting serialization with json.load() and json.loads().
What you can do after
Apply it via Python’s json module to write one valid JSON structure to a file.
How it connects
Connects json.dump() with json.dumps(), json.load(), json.loads(), and JSON-to-Python type conversion.

Also explained in

Compare how 3 books explain json.dump() →

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.