JSON Write in Python

Write a Python dictionary as JSON into a file.

BeginnerFile Handling ProgramsExample 7 of 20
json-write.py
Run in browser
1# Program to write JSON to a file
2
3import json
4
5data = {
6 "name": "Alice",
7 "age": 25,
8 "skills": ["Python", "SQL"]
9}
10
11filename = input("Enter JSON filename to write: ")
12
13with open(filename, "w", encoding="utf-8") as f:
14 json.dump(data, f, indent=2)
15
16print("JSON data written to", filename)

Output

Enter JSON filename to write: config.json
JSON data written to config.json

What's going on

json.dump serializes Python objects to JSON text and writes them to a file with pretty indentation.