Write Dict to JSON File
Serialize a Python dictionary to a JSON file.
Code
Python
import json
data = {"name": "Alice", "scores": [90, 85, 88]}
with open("output.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
print("Written successfully")Line-by-line explanation
- 1.Import the json module.
- 2.Define a dictionary (or list) to serialize.
- 3.Open a file in write mode.
- 4.Use json.dump() with indent=2 for pretty-printing.
- 5.The file is written and closed automatically.
Expected output
Written successfully