Pylerno
English

JSON

Convert between data, JSON text, and a file without confusing their roles.

On this page

The concept

JSON is a data format, not Python code. Dictionaries become JSON objects, lists become arrays, True becomes true, and None becomes null. dumps/loads operate on strings; dump/load operate on open file objects. ensure_ascii=False preserves readable non-ASCII text when present.

Successfully parsing JSON proves only that its syntax is valid. Your program must still check its structure and domain rules: a JSON list is not a profile dictionary just because both parse. Corrupt content and a missing file are different conditions and should not be treated as identical empty data.

Worked example

python
import json
from pathlib import Path
from tempfile import TemporaryDirectory

student = {"name": "Sara", "scores": [80, 95], "active": True}
text = json.dumps(student, ensure_ascii=False, indent=2)
print(text)
restored = json.loads(text)
print(restored["name"])
with TemporaryDirectory(prefix="python_json_") as temporary:
    path = Path(temporary) / "student.json"
    with path.open("w", encoding="utf-8") as file:
        json.dump(student, file, ensure_ascii=False, indent=2)
    with path.open(encoding="utf-8") as file:
        loaded = json.load(file)
    print(loaded == student)

Trace the result

  1. dumps creates a formatted text representation of the student record.
  2. loads reconstructs Python data from that representation.
  3. The temporary file round trip uses dump and load and checks value equality.
text
{
  "name": "Sara",
  "scores": [
    80,
    95
  ],
  "active": true
}
Sara
True
Line-by-line walkthrough

Line 1: import json

Load json (JSON serialization and parsing). Importing makes these names available; it is not a call to every function in the module.

Line 2: from pathlib import Path

Import Path from pathlib. This supplies filesystem path values. The caller can now use the imported names directly.

Line 3: from tempfile import TemporaryDirectory

Import TemporaryDirectory from tempfile. This supplies temporary files and directories. The caller can now use the imported names directly.

Line 5: student = {"name": "Sara", "scores": [80, 95], "active": True}

Evaluate {'name': 'Sara', 'scores': [80, 95], 'active': True}, then bind or update student with the result. The chosen collection determines how later access, membership, and mutation behave. Assignment itself does not imply a deep copy.

Line 6: text = json.dumps(student, ensure_ascii=False, indent=2)

Evaluate json.dumps(student, ensure_ascii=False, indent=2), then bind or update text with the result. The call finishes before its return value is bound; a failed call does not produce a successful assignment. Assignment itself does not imply a deep copy.

Line 7: print(text)

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Line 8: restored = json.loads(text)

Evaluate json.loads(text), then bind or update restored with the result. The call finishes before its return value is bound; a failed call does not produce a successful assignment. Assignment itself does not imply a deep copy.

Line 9: print(restored["name"])

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Lines 10–16: with TemporaryDirectory(prefix="python_json_") as temporary:

Enter the listed context manager(s), run the indented block, and leave each context afterward. The manager defines the cleanup/commit behavior; a database transaction and a file lifetime are not identical contracts.

Line 11: path = Path(temporary) / "student.json"

Evaluate Path(temporary) / 'student.json', then bind or update path with the result. Assignment itself does not imply a deep copy.

Lines 12–13: with path.open("w", encoding="utf-8") as file:

Enter the listed context manager(s), run the indented block, and leave each context afterward. The manager defines the cleanup/commit behavior; a database transaction and a file lifetime are not identical contracts.

Line 13: json.dump(student, file, ensure_ascii=False, indent=2)

Call json.dump with the displayed arguments. This call may have an effect even when its return value is not assigned.

Lines 14–15: with path.open(encoding="utf-8") as file:

Enter the listed context manager(s), run the indented block, and leave each context afterward. The manager defines the cleanup/commit behavior; a database transaction and a file lifetime are not identical contracts.

Line 15: loaded = json.load(file)

Evaluate json.load(file), then bind or update loaded with the result. The call finishes before its return value is bound; a failed call does not produce a successful assignment. Assignment itself does not imply a deep copy.

Line 16: print(loaded == student)

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Common mistake

Do not use eval to read JSON. Do not silently replace malformed stored data with an empty collection that may later overwrite it.

Check your understanding

What does this program print?

python
import json
print(json.loads('{"n": 4}')["n"] + 1)
Choose one answer

Search documentation

Share this page