JSON
JSON is the text format the web uses to exchange data. It looks almost exactly like Python dicts and lists.
import json data = json.loads('{"a": [1, 2]}') # text -> Python text = json.dumps(data) # Python -> text
JSON uses lowercase true, false, and null inside its text. loads converts them to Python True, False, and None; dumps converts them back.
See it run
import json order = {"id": 7, "tags": ["new", "gift"], "paid": True} text = json.dumps(order) back = json.loads(text) back["paid"] = False print(text) print(order["paid"])
JSON is just text. dumps turns Python data into it, loads turns it back.
Practice json
Exercise 1
- Parse
textfrom the code editor below intodata. first_skill= the first item ofdata["skills"].- Add the key
"level"with3to data, then turn it back into a stringback.
Exercise 2
Parse the shipment JSON in text in the code editor below into shipment. Sum quantities from every item into units; keep zero quantities. Add "units" to shipment and serialize the complete updated object into back.
Exercise 3
Write active_names(text) for a JSON list of user objects. Return a JSON string containing only the names whose active field is true; a missing active field means false. Preserve order and repeated names, and support an empty list.
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.