JSON and CSV · practice
Write the JSON Document
The converter now holds ordinary Python values with the right meaning. The json
Build the envelope first
The
document = {
"schema_version": 1,
"items": items,
}
That Python str(document): Python spells True and False, while JSON requires true and false; quoting and escaping have more cases than one example reveals.
dump writes to a file
json.dump(value, handle, ...) serializes directly into an open text file:
with open(path, "w", encoding="utf-8") as handle:
json.dump(document, handle, ensure_ascii=False, indent=2, allow_nan=False)
handle.write("\n")
ensure_ascii=FalsekeepsCaféreadable in the UTF-8 file.indent=2gives deterministic, reviewable output.allow_nan=Falserefuses non-finite numbers that JSON’s standard does not contain.json.dumpdoes not add a final newline, so the file contract adds one.
The s names the json.dumps(document) returns JSON text as a Python string, while json.dump(document, handle) writes to an open file. Both serialize one load reads an open file and loads parses a string. Lesson 5 uses that reading pair.
Your turn
Implement write_catalog_json(items, path) and convert_catalog(input_path, output_path).
write_catalog_json builds the exact envelope, writes it with the options above, and returns the document it wrote. convert_catalog reads and converts the CSV through read_catalog_csv, passes those items to the writer, and returns the same document.
Run the project after implementing the two main is still a no-op until Lesson 6. The checks call the functions directly and inspect the actual output file. They also use an unseen CSV, so a hard-coded copy of the seeded JSON cannot pass.
Why not build the JSON text with an f-string?
What is the difference between json.dump and json.dumps?
Task
Implement write_catalog_json(items, path) and convert_catalog(input_path, output_path).
Write the exact {schema_version, items} document with json.dump, UTF-8, ensure_ascii=False, two-space indentation, allow_nan=False, and one final newline. Return the same document from both