Skip to chapter content
navan✳THE BUILD LABPYTHON / GUIDE
0/26 read
CHAPTER 18 / 26 · DOCUMENTS AND SERVICES

CSV, JSON, and XML.

Choose a data format, parse it safely, and preserve the meaning of each field.

BY NAVAN SAMI5 MIN READTHEORY FIRST
01 / THE BASICS

Start here.

CSV, JSON, and XML are formats for exchanging data, but they describe structure differently. CSV is row-and-column oriented and works well for a table. JSON expresses objects, arrays, strings, numbers, booleans, and null. XML uses nested elements and attributes. A parser knows each format's quoting and escaping rules and produces Python values you can inspect; a plain split or string replacement usually does not understand enough of the format.

The csv module reads rows, and DictReader can map headings to values. Those values arrive as strings, so a quantity column still needs deliberate conversion. json.loads turns JSON text into Python dictionaries, lists, and primitive values; json.dumps makes JSON text from suitable Python values. XML parsers build element trees, where tags, attributes, text, and children may each carry meaning.

Do not assume parsing proves the data is useful. A syntactically valid JSON object can still omit a required field, and a CSV row can have a malformed amount. First parse the format, then validate the particular schema your program expects. Encoding is another layer: bytes must become text before a text parser can interpret them. Keeping those layers separate makes errors easier to explain.

02 / THE IDEA

Build the model.

Automation often connects systems that disagree about how to represent a record. CSV is a table of rows and columns, JSON represents nested objects and arrays, and XML represents nested elements with attributes and text. None of these formats tells you whether a particular field is valid. Parsing gives you Python values; validation gives those values meaning.

Start by writing down a small example record and its required fields. Ask what happens if a column is missing, a number is blank, or a date uses an unexpected format. Decide whether to skip, repair, or reject a bad record before processing a large file. A program that silently accepts malformed input can produce convincing but wrong output.

03 / UNDER THE SURFACE

How it works.

Use the csv module for CSV because commas inside quoted fields and line endings have rules that split(',') does not handle. csv.DictReader maps column names to values, but every value arrives as text. Open CSV files with newline='' and a deliberate encoding. For JSON, json.load reads a file and json.dump writes Python-compatible values; JSON has no tuple, set, or arbitrary class object, so convert those deliberately.

XML is useful when element order, attributes, or mixed text and markup matter. ElementTree can parse trusted, modest XML documents and find elements by path. For XML from untrusted sources, use a hardened parser and set resource limits: maliciously crafted documents can consume excessive resources. Across all three formats, keep parsing separate from the rule that says a row is a valid order or customer.

A good import pipeline has four stages: read bytes as text, parse the format, validate a record, and transform it into the program's own model. This separation makes errors specific. 'Invalid JSON' is different from 'missing customer_id', and both differ from 'negative quantity'. Write output to a fresh file first and inspect a few records before replacing a source.

04 / A WORKED EXAMPLE

Read it line by line.

example.py
import csv
from pathlib import Path
with Path('orders.csv').open(newline='', encoding='utf-8') as file:
    for row in csv.DictReader(file):
        quantity = int(row['quantity'])
        print(row['item'], quantity)

DictReader uses the first row as field names and yields one dictionary per later row. The code retrieves item as text and converts quantity to an integer. If the field is absent, KeyError makes that contract failure visible; if it is not a number, int raises ValueError. A production importer can catch those per row and report the row number.

05 / ANOTHER EXAMPLE

See the rule again.

example-2.py
import json
record = json.loads('{"item": "Pen", "price": 4, "quantity": 3}')
if record['quantity'] < 0:
    raise ValueError('quantity must be nonnegative')
print(record['price'] * record['quantity'])

json.loads turns the string into a dictionary; the explicit rule rejects a negative quantity. The output is 12. JSON syntax validity alone would not have checked that business rule.

06 / REMEMBER THIS

A mistake to avoid.

Never parse CSV by splitting each line on commas. A field such as "Dubai, UAE" is one cell when correctly quoted. The csv module understands that rule.

Finished this chapter?
Built with curiosity. By Navan Sami. ↗Python · Understand the idea, then write the code.