0%

JSON and CSV · practice

Write the JSON Document

The converter now holds ordinary Python values with the right meaning. The json ’s job is to serialize them: turn the in-memory into JSON text with the required escaping and punctuation.

Build the envelope first

The of items belongs under the exact top-level schema:

document = {
    "schema_version": 1,
    "items": items,
}

That Python is the document’s logical shape. Serialization is a separate operation. Do not assemble JSON with or 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=False keeps Café readable in the UTF-8 file.

  • indent=2 gives deterministic, reviewable output.

  • allow_nan=False refuses non-finite numbers that JSON’s standard does not contain.

  • json.dump does not add a final newline, so the file contract adds one.

The s names the version: json.dumps(document) returns JSON text as a Python string, while json.dump(document, handle) writes to an open file. Both serialize one . The same pairing works in reverse: 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 only if you also call them temporarily yourself; 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 .