hayaliv / Hi! Python / Level 1
JSON
Turn Python data into JSON text and back with json.dumps and json.loads.
Think of it like this
JSON is like writing a recipe on a card so a friend can cook it later. You write it down in a shared format, and your friend reads it back into their own kitchen.
Where the analogy stops being true. A recipe card does not change by itself, but JSON can change your data: a tuple comes back as a list and an integer dict key comes back as a string.
What to know
json.dumpsturns a Python object into a JSON string, andjson.loadsturns a JSON string back into a Python object.- A dict becomes a JSON object, a list or tuple becomes an array, and
True,FalseandNonebecometrue,falseandnull. indent=2pretty-prints the result, andsort_keys=Truesorts dictionary keys.- By default
ensure_ascii=Trueescapes every non-ASCII character, so a letter such asëturns into a\u00ebcode. - With
ensure_ascii=Falsethe characters are written as they are, which is easier for people to read. - A round trip
json.loads(json.dumps(x))gave back an equal dict in our example (the output shows True).
Example
import json
record = {"input": "Mirëdita", "label": "meeting_request", "score": 0.9, "tags": ["warm", None], "seen": True}
print(json.dumps(record["input"]))
text = json.dumps(record, ensure_ascii=False, sort_keys=True)
print(text)
print(json.loads(text) == record)
print(json.dumps({"b": [1, 2], "a": 1}, indent=2, sort_keys=True))
It prints:
"Mir\u00ebdita"
{"input": "Mirëdita", "label": "meeting_request", "score": 0.9, "seen": true, "tags": ["warm", null]}
True
{
"a": 1,
"b": [
1,
2
]
}
Predict, then check
1. What does this print?
import json
print(json.dumps({"ok": True, "x": None, "t": (1, 2)}))Show the answer
{"ok": true, "x": null, "t": [1, 2]}True, None and a tuple map to true, null and an array.
2. What does this print?
import json
print(json.loads(json.dumps({1: "a"})))Show the answer
{'1': 'a'}JSON object keys are always strings, so the integer key 1 comes back as the string '1'.
3. What does this print?
import json
print(json.dumps("Mirëdita", ensure_ascii=False) == '"Mirëdita"')Show the answer
TrueWith ensure_ascii=False the Albanian characters are written as they are, only wrapped in quotation marks.
Try it
Write pretty(record). It returns the record as JSON text with indent=2, sorted keys, and non-ASCII characters left as they are.
import json
def pretty(record):
return json.dumps(record)
Show a solution
import json
def pretty(record):
return json.dumps(record, indent=2, sort_keys=True, ensure_ascii=False)Common mistake
A dict with integer keys does not round trip: the keys come back as strings (see predict item 2). A tuple also comes back as a list.
In a small-language-model project
Each training example is usually a small dict such as {"input": ..., "label": ...}. json.dumps with ensure_ascii=False keeps Albanian replies readable when you open the saved data to check it by eye.
Sources
Each quote below appears word for word on the cited page of the official Python documentation (version 3.12).
Serialize obj to a JSON formatted str using this conversion table .
docs.python.org/3.12/library/json.html — dumps returns a JSON formatted str.deserialize s (a str , bytes or bytearray instance containing a JSON document) to a Python object
docs.python.org/3.12/library/json.html — loads reads a JSON document held in a str.list, tuple array str string int, float, int- & float-derived Enums number True true False false None null
docs.python.org/3.12/library/json.html — Python types map to JSON types.JSON Python object dict array list string str number (int) int number (real) float true True false False null None
docs.python.org/3.12/library/json.html — JSON arrays decode to Python lists.Keys in key/value pairs of JSON are always of the type str .
docs.python.org/3.12/library/json.html — Dict keys become strings in JSON.If True (the default), the output is guaranteed to have all incoming non-ASCII characters escaped.
docs.python.org/3.12/library/json.html — ensure_ascii=True escapes non-ASCII characters.If False , these characters will be outputted as-is.
docs.python.org/3.12/library/json.html — ensure_ascii=False writes characters as they are.A positive integer indents that many spaces per level
docs.python.org/3.12/library/json.html — indent pretty-prints.If True , dictionaries will be outputted sorted by key.
docs.python.org/3.12/library/json.html — sort_keys sorts dictionary output by key.