0%

Chapter 7

JSON and CSV

One Catalog, Two Shapes

The project beside this chapter begins with catalog.csv. By the end, catalog.py will turn it into catalog.json and will be able to read that JSON back without guessing what any means.

Before writing the converter, fix the contract. A data format tells you how text is arranged. A schema says which arrangement this project accepts.

CSV is a table of text

The first line names five columns:

sku,name,quantity,unit_price,in_stock

Each data record is one row. A quoted cell can contain a newline, so a row can span several physical lines. A comma inside a cell also needs CSV quoting, as in the second product’s name:

GM-204,"Dice, Set of 6",0,7.25,false

CSV does not mark 0 as an integer or false as a . A CSV reader gives the program text cells. The schema has to say which conversions are allowed. For this project:

  • sku and name become non-empty after surrounding spaces are removed;

  • quantity becomes an integer of zero or more;

  • unit_price becomes a finite number of zero or more;

  • in_stock accepts only lowercase true or false, then becomes a boolean.

The exact rules live in SCHEMA.md. Keep that file open when a later exercise asks whether a value is valid. Examples are useful; the written contract wins.

JSON keeps container shape and value type

One converted item has this JSON shape:

{
  "sku": "GM-204",
  "name": "Dice, Set of 6",
  "quantity": 0,
  "unit_price": 7.25,
  "in_stock": false
}

The braces make an , much like a Python . The product name is a string, 0 is a number, and false is a boolean. Those distinctions are part of the data.

The complete output is not a bare item or a bare array. Its top level is an object with exactly two fields:

{
  "schema_version": 1,
  "items": []
}

items will contain one object per CSV row, in the same order. Keeping the version beside the items gives a future reader a place to decide which schema it is looking at.

After csv.DictReader reads a valid row, what is the value of its quantity cell before this project converts it?

Which value matches the declared top-level JSON shape?

The next lesson reads only the CSV structure: header, rows, and cell count. It deliberately leaves every cell as text. Type conversion is a separate boundary and deserves its own checks.