Skip to main content
← Python Study Guide

Code Scholars Tutoring · Python

5.2 Structured Formats

How it works

CSV and JSON carry structure that plain text does not. Parsing with the right module avoids hand-splitting that breaks on quoted fields.

Use the CSV module rather than splitting on commas, because a quoted field may contain one.

Common error

Splitting a CSV line on commas, which corrupts any row containing a quoted comma.

Worked example

Python

import json
payload = '{"name":"Ada","scores":[4,7]}'
data = json.loads(payload)
print(data["name"], sum(data["scores"]))

Output

Ada 11

Structured formats preserve relationships between fields. JSON parsing produces Python objects, but a successful parse does not prove the expected fields or value types are present.

Exercises

5.2.1 · Trace

Determine the exact output and explain the state changes.

Python

import csv
from io import StringIO
rows = list(csv.DictReader(StringIO("name,score\nAda,7\n")))
print(rows[0]["score"], type(rows[0]["score"]).__name__)
Show solution

Output

7 str

CSV reader fields are strings until the program performs appropriate conversion.

5.2.2 · Write code

Parse the JSON list [2, 5, 8] and print its largest value.

Show solution

Load the structure, then use the appropriate list operation.

One valid solution

import json
values = json.loads("[2, 5, 8]")
print(max(values))

Expected output

8
Open Python compiler

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic