The bus company problem
A bus company sends your school a list of seats for a trip. The list is a spreadsheet file.
Your school app needs the same list, but it can only read one other format. So somebody must change the list from one format to the other.
Which format is best for each job? And what can go wrong when you change it?
Key words
| Word | What it means | Example |
|---|---|---|
| Data format | The way data is written in a file. | CSV, JSON, XML |
| CSV | Rows of values split by commas, all stored as text. | Sam,16,12.5 |
| JSON | Names and values in curly brackets { }, keeping numbers, true or false, and lists. | {"age": 16} |
| XML | Tags inside tags, all stored as text. | <age>16</age> |
| Transformation | Changing data from one form to another. | CSV to JSON |
| Integer | A whole number. | 16 |
| Float | A number with a decimal point. | 12.5 |
| Casting | Changing a value from one kind to another. | int("16") |
| Flat data | Data in simple rows and columns, with nothing inside a cell. | A spreadsheet |
| Nested data | Data with other data inside it. | A student with a list of trips |
| Dictionary | In Python, names that each hold a value. | {"name": "Sam"} |
| Parse | To read text in a format and turn it into data a program can use. | Turn CSV lines into a list |
The cells students fill in are left blank in this preview.
Try it: the same data three times
csv_text = "name,age\nSam,16\nAisha,17"
json_text = '[{"name": "Sam", "age": 16}, {"name": "Aisha", "age": 17}]'
xml_text = '<students><student><name>Sam</name><age>16</age></student><student><name>Aisha</name><age>17</age></student></students>'
print("CSV ", len(csv_text), "characters")
print("JSON ", len(json_text), "characters")
print("XML ", len(xml_text), "characters")
# Which one is the smallest? Which one is the biggest?
Make a free account to save your work and track your progress.
What each format keeps
| Question | CSV | JSON | XML |
|---|---|---|---|
| Does it keep numbers and True or False? | No, all text | Yes | No, all text |
| Can it hold a list inside a record? | No, flat only | Yes | Yes |
| How big is the file? | Smallest | Middle | Biggest |
| Does it open in a spreadsheet? | Yes | Not easily | Not easily |
| Common use | Tables and files saved from a spreadsheet | Web and apps | Documents and older systems |
The cells students fill in are left blank in this preview.
Quick check: reading the table
Have a go
Quick check: reading the table
3 questionsChanging format needs care
When you change a format you do a transformation. You parse the old format, then write the new one.
CSV has only text. So going from CSV to JSON, you must cast the age to an integer and the money to a float. If you forget, the data keeps "16" as text.
Try it: CSV text to a list
text = "name,age\nSam,16\nAisha,17"
people = []
lines = text.split("\n")
for i in range(1, len(lines)):
parts = lines[i].split(",")
people.append({"name": parts[0], "age": int(parts[1])})
print(people)
# range(1, len(lines)) skips line 0, the heading line.
# This list has the same shape as JSON. Remove int( ) and see what changes.
Make a free account to save your work and track your progress.
Extra: Python's own csv and json tools
# Python has tools that parse CSV and write JSON for you.
import csv
import json
text = "name,age\nSam,16\nAisha,17"
people = []
for row in csv.DictReader(text.split("\n")):
people.append({"name": row["name"], "age": int(row["age"])})
print(json.dumps(people))
# json.dumps writes real JSON text. Remove int( ) and see the quotes come back.
Make a free account to save your work and track your progress.
Nested data does not fit in a CSV
Warning
Many people think any data fits in a CSV. It fits only when the data is flat, because a CSV has no place for a list. So a student's list of trips cannot stay a list. You must join the trips into one cell or make a row for each trip. Both lose some of the shape.
Match the job to the best format
Have a go
Loading…
Your answers are marked here and are not kept. A college account keeps every student’s marks.
Watch: choosing a format
Press Play on the short film below. It starts with the bus company's list. Then it shows the same data in three formats, what can go wrong when you change one, and two myths.
Film: Choosing and changing a data format
Choosing and changing a data format
Every scene, as text
- The bus company problem. The list of seats: a spreadsheet file. Your school app can only read one other format. Somebody must change the list from one format to the other (transformation: from one form to another).
- Data format: the way data is written in a file. Sam,16,12.5 (CSV: values split by commas, all text). {"age": 16} (JSON: numbers, true or false, and lists). <age>16</age> (XML: tags inside tags, all text).
- Two students, three times. CSV: 24 characters (size: smallest). JSON: 58 characters (size: middle). XML: 119 characters (size: biggest; why: an opening and a closing tag).
- Changing format needs care. Sam,16,12.5 (CSV: only text). {"paid": "12.5"} (problem: the money stays as text). {"paid": 12.5} (fix: casting makes it a float).
- Myth (false): any data fits in a CSV. That is not true. A student with a list of trips (CSV: no place for a list; nested data: data with other data inside it). Join the trips into one cell. Or make a row for each trip (both: lose some of the shape).
- Myth (false): JSON is best for everything. That is not true. Weekly sales numbers for a graph (CSV: one row per week, easy to load; CSV: opens in a spreadsheet). A museum document with sections inside sections (XML: tags can nest as deep as you like). Settings for a web app, with a list of colours (JSON: it holds lists and named values).
Your turn: change the format
Write two functions. The first changes CSV text into a list of dictionaries, the same shape as JSON. Age must be an integer and paid must be a float. The second changes the list back into CSV text. Press Run Tests to check.
def csv_to_people(text):
# text is CSV with the headings name,age,paid. Lines are split by a newline.
# Give back a list with one dictionary for each person after the heading line.
# Example dictionary: {"name": "Sam", "age": 16, "paid": 12.5}
# age must be an integer and paid must be a float, not text.
# Hint: text.split("\n"), line.split(","), int(...), float(...)
return None
def people_to_csv(people):
# people is a list of dictionaries like the one above.
# Give back CSV text. The first line is: name,age,paid
# Put a newline between lines. Do not put one at the end.
return None
Make a free account to save your work, or press Start lab to work through the whole lesson.
Which format should I use?
Your turn: argue for a format
A football club wants an app that shows match results. Results come from a spreadsheet each week. The app gets its data from a server (a computer on the internet). Write 4 to 6 short sentences. Say which format is best for the spreadsheet saved as a file. Say which format the app and server use, and why. Say one thing that could go wrong when you change from one to the other.
A teacher marks this in a college. Nothing you write here is kept: it goes when you leave the page.
Make a free account to save your work, or press Start lab to work through the whole lesson.
Final check
Have a go
Final check
5 questionsRemember
Important
CSV is flat and small. JSON is for apps and keeps types and lists. XML is for tags inside tags. A transformation needs parsing, casting and care.