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.
- Import
json. - Create
dataas a dictionary with keys"name"set to"Alice","scores"set to[95, 88, 92], and"active"set toTrue. - Open
student.jsonin write mode. Calljson.dump(data, file, indent=2). - Call
print("student.json written successfully."). - Assign
json.dumps(data, indent=2)tooutput. Callprint(output).
# Step 1: Import json # Step 2: Create data dict with name, scores, and active fields # Step 3: Open student.json and write data with indent=2 # Step 4: Print "student.json written successfully." # Step 5: Convert data to formatted JSON string and print it
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding