Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Preview

Choosing and changing a data format

This is the first page of the lesson. Read it and have a go at the activities. The rest is in the full lesson.

45 minutes

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? Let us find out.

Key words

WordWhat it meansExample
Data formatThe way data is written in a file.CSV, JSON, XML
CSVRows with commas between the values. Everything is text.Sam,16,12.5
JSONCurly brackets { }, names and values. It has numbers, text, true and false, and lists.{"age": 16}
XMLTags inside tags. Everything is text.<age>16</age>
TransformationChanging data from one form to another.CSV to JSON
IntegerA whole number.16
FloatA number with a decimal point.12.5
CastingChanging a value from one kind to another, such as text to a number.int("16")
Flat dataData in simple rows and columns, with nothing inside a cell.A spreadsheet
Nested dataData with other data inside it, such as a list inside a record.A student with a list of trips
DictionaryIn Python, a set of names with a value for each name.{"name": "Sam"}
ParseRead text in a format and turn it into data your 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

Code: python
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?

What each format keeps

QuestionCSVJSONXML
Does it keep numbers and True or False?No, all textYesNo, all text
Can it hold a list inside a record?No, flat onlyYesYes
How big is the file?SmallestMiddleBiggest
Does it open in a spreadsheet?YesNoNot easily
Common useTables and files saved from a spreadsheetWeb and appsDocuments 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 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Changing 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

Code: python
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.

Extra: Python's own csv and json tools

Code: python
# 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.

Nested data does not fit in a CSV

data-callouts.warning.label

A CSV is flat. If a student has a list of trips, a CSV cannot keep the list. You must join the trips into one cell or make a row for each trip. Both lose some of the shape.

The lesson goes on

6 more parts of this lesson are in the full curriculum, with the tasks, the final check and the labs. A college account gives your students all of it.