python · level 2 · unit 5 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
turns your data into text, and json turns it back.
Programs share data as text, and the favourite format is JSON. It looks almost like Python: curly brackets, square brackets, colons and commas. A weather app, a game and a website can all read it.
json.dumps(data) turns dictionaries and lists into a JSON string. json.loads(text) does the opposite: it parses JSON text back into dictionaries and lists. Remember the s: dump string, load string.
JSON uses double quotes only, and writes true, false and null where Python writes True, False and None. Wrap JSON text in single quotes in your code, so its double quotes do not end the string.
import json
pet = {"name": "Rex", "age": 3, "vaccinated": True, "chip": None}
text = json.dumps(pet)
print(text)
back = json.loads(text)
print(back["name"], back["vaccinated"]) json.dumps(pet, indent=2) spreads the JSON over several lines, one pair per line.
guess first
Text in, data out. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import json
reply = '{"city": "Leeds", "temps": [9, 12, 11]}'
data = json.loads(reply)
print(len(data))
print(data["temps"][1])
your turn
Your turn. Save a high score table as JSON.
Add two players and their scores. Then fill in the function that turns a dictionary into JSON text.
fix it
The weather reader crashes. Can you fix it?
- Read the error: TypeError. What type is
dataafter line 3? dumpsturns data into text, butreplyis already text. You need the function that parses text into data.- Change json.dumps to json.loads on line 3, then run.
nailed it
you speak json now. :D
- JSON is text that holds dictionaries and lists.
json.dumpsturns data into text,json.loadsparses it back.- JSON writes
true,falseandnullin small letters.
new words in your collection
- JSON
- parse
This lesson isn’t saved. A free account remembers every lesson you finish.