Files, Errors and Modules · Working at Scale · lesson 7 of 8
JSON in and out
about 14 minutes · free · runs in your browser
Step 1 of 2
Text in, objects out
JSON is how programs exchange structured data. The json module converts both ways:
import json
text = json.dumps({"name": "Ada", "age": 36}) # object → string
data = json.loads('{"name": "Ada"}') # string → object
Remember which is which by the s: dumps and loads work with strings, while
dump and load work with files.
The mapping is close but not exact. Python's None becomes null, True becomes
true, and both tuples and lists come back as lists. Dictionary keys are always strings
in JSON, so {1: "a"} returns as {"1": "a"}.
json.dumps(data, indent=2) gives readable output, and sort_keys=True makes it
stable — which matters if you ever compare two files.
Malformed text raises json.JSONDecodeError, a subclass of ValueError.
Your turn: write parse_config(text) returning the parsed dictionary, or an empty
dictionary when the text is not valid JSON.
You start from this, and edit it in the browser:
import json
def parse_config(text):
# Parse the JSON, or return {} when it is malformed.
pass
Step 2 of 2
Writing JSON back out
json.dumps turns Python data into text you can store or send.
Your turn: write to_json(records) returning the list as JSON with keys sorted and
no spaces wasted — use separators=(",", ":") for the compact form.
You start from this, and edit it in the browser:
import json
def to_json(records):
# Return compact JSON with sorted keys.
pass