JSON Structure
Unit ID: M07-U04 Estimated active time: 22-30 minutes
JSON represents common structured values
JSON supports objects, arrays, strings, numbers, booleans, and null. Python's json module maps these to dictionaries, lists, strings, numbers, booleans, and None.
Write JSON
import json
records = [
{"code": "AI-01", "hours": 8, "available": True},
]
with output_path.open("w", encoding="utf-8") as file:
json.dump(records, file, indent=2, ensure_ascii=False)
file.write("\n")
Indentation improves review. ensure_ascii=False preserves readable Unicode characters in UTF-8 output.
Read JSON
with output_path.open("r", encoding="utf-8") as file:
loaded_records = json.load(file)
Inspect the top-level type and required fields. Successful parsing does not prove the data matches your task schema.
JSON is data, not executable Python
Use json.load() or json.loads(). Do not use eval() to parse JSON or other untrusted text.
JSON limitations
Tuples become arrays and load back as lists. Sets are not directly JSON serialisable. Dictionary keys in JSON are strings. Special Python objects need an explicit representation.
Malformed JSON
Missing commas, extra trailing commas, and incorrect quoting can raise json.JSONDecodeError. Preserve the file and report the error location rather than rewriting it silently.
Practice
Write a fictional accepted-record list to JSON, read it back, and assert equality. Then add an unsupported set value and inspect the TypeError without changing the original record.
Takeaway
JSON stores nested interoperable data, but parsing and schema validation are separate steps. Use the JSON module, explicit UTF-8, and reviewed representations. Next, we will handle missing, malformed, and unexpected files.
