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

Free lesson

6.5 (2 of 3): Choosing and changing a data format

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

45 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

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

WordWhat it meansExample
Data formatThe way data is written in a file.CSV, JSON, XML
CSVRows of values split by commas, all stored as text.Sam,16,12.5
JSONNames and values in curly brackets { }, keeping numbers, true or false, and lists.{"age": 16}
XMLTags inside tags, all stored as 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.int("16")
Flat dataData in simple rows and columns, with nothing inside a cell.A spreadsheet
Nested dataData with other data inside it.A student with a list of trips
DictionaryIn Python, names that each hold a value.{"name": "Sam"}
ParseTo 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

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?

Make a free account to save your work and track your progress.

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?YesNot easilyNot 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

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.

Make a free account to save your work and track your progress.

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.

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

  1. 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).
  2. 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).
  3. 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).
  4. 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).
  5. 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).
  6. 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.

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

A flowchart: from "Start: what is the data?" to "Plain words with no shape?", where yes leads to "Text file" and no to "Does it have data inside data?", where no leads to "Will a spreadsheet open it?" (yes "CSV", no "JSON") and yes leads to "Is it for a web page or an app?" (yes "JSON", no "XML, if the other system asks for it").A flowchart: from "Start: what is the data?" to "Plain words with no shape?", where yes leads to "Text file" and no to "Does it have data inside data?", where no leads to "Will a spreadsheet open it?" (yes "CSV", no "JSON") and yes leads to "Is it for a web page or an app?" (yes "JSON", no "XML, if the other system asks for it").

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 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

Remember

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.

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.