One list, four ways to write it
You have a list of three students on a school trip. You must send it to another program.
You can write it as plain words. You can write it with commas. You can write it with curly brackets. Or you can write it with tags.
All four hold the same facts. But each one suits a different job.
Key words
| Word | What it means | Example |
|---|---|---|
| Data format | The way data is written in a file. | CSV, JSON, XML |
| Text file | A file of plain characters with no fixed shape. | notes.txt |
| CSV | Comma separated values: one row per line, with commas between values. | Sam,16,12.50 |
| JSON | A format of names, values and lists in curly brackets. | {"name": "Sam"} |
| XML | A format of tags in angle brackets, which can sit inside each other. | <student>Sam</student> |
| Tag | A label in angle brackets that starts or ends a piece of XML. | <student> |
| Attribute | An extra fact written inside the opening tag. | age="16" |
| 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. | Split a CSV line into its values |
The cells students fill in are left blank in this preview.
The four formats
| Format | What it looks like | Best for |
|---|---|---|
| Text file | Plain words, any shape | Notes, logs, a story |
| CSV | Rows, with commas between values | Tables that open in a spreadsheet |
| JSON | Curly brackets { }, names and values | Web pages talking to servers, settings |
| XML | Tags inside tags, in angle brackets < > | Documents with parts inside parts, and older systems |
The cells students fill in are left blank in this preview.
Try it: CSV
text = "name,age,paid\nSam,16,12.50\nAisha,17,5.00"
print(text)
lines = text.split("\n")
lines.pop(0) # take off the headings line
for line in lines:
values = line.split(",")
print(values[0], "paid", values[2])
# Everything from a CSV is a string (text). Try float(values[2]).
Make a free account to save your work and track your progress.
Quick check: which format?
Have a go
Quick check: which format?
4 questionsJSON in plain words
JSON holds names and values. A name is in quote marks. A colon sits between the name and the value.
A value can be text or a number. It can be true or false. It can be a list in square brackets. A web page and a server often use JSON to talk.
Try it: JSON
# JSON looks like a Python dictionary.
text = '{"trip": "Zoo", "price": 12.5, "students": ["Sam", "Aisha"], "coach": true}'
print(text)
# JSON writes true. Python writes True.
data = {"trip": "Zoo", "price": 12.5, "students": ["Sam", "Aisha"], "coach": True}
print(data["trip"])
print(data["students"])
print(len(data["students"]))
Make a free account to save your work and track your progress.
JSON is strict
Warning
Many people think JSON allows everything that Python allows. It does not. JSON needs double quote marks ("like this"), not single ones. It allows no comma after the last item. One small mistake and the whole file will not parse.
XML in plain words
XML puts every piece of data between an opening tag and a closing tag, such as <student>Sam</student>.
A tag can sit inside another tag. The top tag is called the root. Extra facts go in attributes, inside the opening tag, such as age="16".
Try it: XML
text = '<trip><student age="16">Sam</student><student age="17">Aisha</student></trip>'
print(text)
names = ["Sam", "Aisha", "Ben"]
xml = "<trip>"
for name in names:
xml = xml + "<student>" + name + "</student>"
xml = xml + "</trip>"
print(xml)
Make a free account to save your work and track your progress.
Extra: Try it: Python's own parsers
# Python has tools that parse JSON and XML for you.
import json
import xml.etree.ElementTree as ET
text = '{"trip": "Zoo", "price": 12.5, "students": ["Sam", "Aisha"], "coach": true}'
data = json.loads(text) # JSON text to a dictionary
print(data["students"])
print(json.dumps(data)) # a dictionary back to JSON text
text = '<trip><student age="16">Sam</student><student age="17">Aisha</student></trip>'
root = ET.fromstring(text) # the root tag, trip
for student in root.findall("student"):
print(student.text, student.get("age"))
# Change a double quote mark in the JSON to a single one. What happens?
Make a free account to save your work and track your progress.
Your turn: read a CSV
The text is a CSV of trip students with the headings name, age and paid. Fill in the two functions. The first gives back the names. The second gives back the total paid as a float. Press Run Tests to check.
def csv_names(text):
# text is CSV with a first line of headings: name,age,paid
# Give back a list of the names, in order. Skip the headings line.
# Hint: text.split("\n") gives the lines. line.split(",") gives the values.
return None
def csv_total(text):
# Give back the total of the paid column as a float.
return None
Make a free account to save your work, or press Start lab to work through the whole lesson.
Your turn: use JSON
You get JSON about a trip as a Python dictionary. Fill in the three functions. Two read it. One writes new JSON text. Press Run Tests to check.
def json_students(data):
# data is a Python dictionary with the same shape as the JSON.
# Give back the list stored under "students".
return None
def json_cost(data):
# Give back the price times the number of students.
return None
def make_json(trip, price):
# Give back JSON text for an object with two names: "trip" and "price".
# For trip "Zoo" and price 12.5 the text is: {"trip": "Zoo", "price": 12.5}
# Hint: join pieces of text with + and use str(price).
return None
Make a free account to save your work, or press Start lab to work through the whole lesson.
Your turn: write XML
You write XML text. One function writes a student tag with an age attribute. One writes a trip tag with a student tag inside it for each name. Press Run Tests to check.
def make_student(name, age):
# Give back XML text for one student. The age is an attribute.
# For Sam, 16 the text is: <student age="16">Sam</student>
return None
def make_trip(names):
# names is a list of names. Give back XML text with a root tag called trip.
# Each name sits inside its own student tag.
# For ["Sam", "Aisha"] the text is:
# <trip><student>Sam</student><student>Aisha</student></trip>
return None
Make a free account to save your work, or press Start lab to work through the whole lesson.
Match the snippet to its format
Have a go
Loading…
Your answers are marked here and are not kept. A college account keeps every student’s marks.
Key words crossword
Have a go
Loading…
Your answers are marked here and are not kept. A college account keeps every student’s marks.
Watch: text, CSV, JSON and XML
Press Play on the short film below. It starts with one list written four ways, then shows the four formats, a CSV, JSON and one myth about it, and XML.
Film: text, CSV, JSON and XML
Text, CSV, JSON and XML
Every scene, as text
- One list, four ways to write it. A list of three students on a school trip. Plain words, commas, curly brackets or tags (four data formats: the same facts). Each one suits a different job.
- The four formats. Remember to bring a packed lunch. (text file: notes, logs, a story). Sam,16,12.50 (CSV: tables that open in a spreadsheet). {"name": "Sam"} (JSON: web pages and servers, settings). <student>Sam</student> (XML: documents with parts inside parts).
- Try it: CSV. name,age,paid then Sam,16,12.50 then Aisha,17,5.00, one a line (first line: the headings; rows: one per line, commas between values). values = line.split(",") (parse: split a line into its values). ['Sam', '16', '12.50'] (a string: everything from a CSV).
- JSON in plain words. One card, a line each: {"trip": "Zoo", (names and values: in curly brackets), "price": 12.5, "students": then ["Sam", "Aisha"], (a list: in square brackets), "coach": true} (true: Python writes it True).
- Myth (false): JSON allows everything that Python allows. {'trip': 'Zoo'} (fine in Python: single quote marks; bad in JSON: single quote marks). That is not true: JSON needs double quote marks, not single ones. {"trip": "Zoo"} (good in JSON: double quote marks). ["Sam", "Aisha",] (bad in JSON: a comma after the last item; one small mistake: the file will not parse).
- XML in plain words. One card, a tag a line: <trip> (root: the top tag), then two spaces in <student>Sam</student> (tags: an opening tag and a closing tag), <student>Aisha</student> (inside the root: three student tags) and <student>Ben</student>, then </trip> (closing tag: every tag must close).
Final check
Have a go
Final check
7 questionsRemember
Important
Text file: plain words. CSV: rows and commas. JSON: curly brackets, names and values. XML: tags inside tags. Parse text to turn it into data.