Errors, files and libraries · Lesson 20 of 25
Exchanging data with JSON
Convert JSON strings to dictionaries and back.
8 minutes2 games
JSON is a text format for data exchange, not Python code. json.loads converts a string to Python objects, and json.dumps converts back. JSON true and null become Python True and None.
Python
import json
raw = '{"name": "Mona", "scores": [80, 95], "active": true}'
student = json.loads(raw)
print(student["name"])
print(sum(student["scores"]))
print(json.dumps({"passed": True, "note": None}, sort_keys=True))| Tool | Use |
|---|---|
| String ↔ object |
| File ↔ object |
What's the output?
import json
print(json.loads('{"ok": true}')["ok"])What will this code print?
Exercise
Decode the JSON and print price plus tax.
Expected output: 114
Python
import json
raw = '{"price": 100, "tax": 14}'
Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.