Writing JSON

Use json.dump() and json.dumps() to save and format JSON data

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Writing JSON to a file

Use json.dump() to write a Python object to a JSON file. The indent parameter makes the output human-readable by adding indentation.

import json

data = {"name": "Alice", "score": 95}

with open("output.json", "w") as file:
    json.dump(data, file, indent=2)

Converting to a JSON string

Use json.dumps() (dump-string) to convert a Python object to a JSON string without writing to a file. This is useful for inspecting the JSON output or sending it over a network.

output = json.dumps(data, indent=2)
print(output)

The indent parameter

Without indent, JSON is written on one line — compact but hard to read. With indent=2, each key gets its own indented line. Use indent=2 for files that humans will read.

Instructions

Write a student record to a JSON file, then convert it to a formatted string.

  1. Import json.
  2. Create data as a dictionary with keys "name" set to "Alice", "scores" set to [95, 88, 92], and "active" set to True.
  3. Open student.json in write mode. Call json.dump(data, file, indent=2).
  4. Call print("student.json written successfully.").
  5. Assign json.dumps(data, indent=2) to output. Call print(output).