7.4 JSON Files
JSON, short for JavaScript Object Notation, is a common data format. It is often used for configuration files, API responses, and simple data exchange. For Python beginners, JSON is approachable because it resembles dictionaries and lists.
JSON and Python Data
Here is a configuration file named settings.json:
json
{
"language": "en",
"theme": "light",
"auto_save": true,
"font_size": 16
}After Python reads it, it becomes a dictionary:
python
import json
with open("settings.json", "r", encoding="UTF-8") as file:
settings = json.load(file)
print(settings["language"])
print(settings["font_size"])json.load(file) reads JSON from a file object and converts it into Python data.
Loading interactive lab...
Loading concept check...
Writing JSON
Use json.dump() to write a Python dictionary back to a JSON file.
python
import json
settings = {
"language": "en",
"theme": "dark",
"auto_save": True,
"font_size": 18
}
with open("settings.json", "w", encoding="UTF-8") as file:
json.dump(settings, file, ensure_ascii=False, indent=2)ensure_ascii=False keeps non-English text readable, and indent=2 makes the JSON easier to inspect.
Loading concept check...
Loading practice...