hayaliv

hayaliv / Hi! Python / Level 1

JSON

Turn Python data into JSON text and back with json.dumps and json.loads.

Hi! Python · Level 1: Files and data · Checked against the Python 3.12 documentation · Updated 2026-10-17

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

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
True

With 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).

Step through this lesson in the Hi! Python desktop

← Text and the `with` statementJSONL-style records: one JSON object per line →