logo
51

JSON Processing

⏱️ 25 min

JSON: Converting Between Text Format and Python Objects

What might confuse you right now

"dict and JSON look the same. Is there a difference?"

Yes. A dict is an in-memory object. JSON is a cross-language text format.

One-line definition

loads/dumps work with strings. load/dump work with files.

Real-life analogy

A dict is like a structure in your head. JSON is like a standardized form you can mail.

Minimal runnable example

import json

user = {"name": "Alice", "age": 25}
text = json.dumps(user, ensure_ascii=False)
print(text)

obj = json.loads(text)
print(obj["name"])

File read/write

with open("user.json", "w", encoding="utf-8") as f:
    json.dump(user, f, ensure_ascii=False, indent=2)

with open("user.json", "r", encoding="utf-8") as f:
    data = json.load(f)

Quick quiz (5 min)

  1. Convert a dict to a JSON string and back.
  2. Write to users.json and read it back.
  3. Filter and output only adult users.

Quiz answer guidelines & grading criteria

  • Answer direction: working code that covers core conditions and edge inputs from the prompt.
  • Criterion 1 (Correctness): Main flow produces correct results, key branches execute.
  • Criterion 2 (Readability): Clear variable names, no excessive nesting.
  • Criterion 3 (Robustness): Basic protection against null values, type errors, or unexpected input.

Transfer task (homework)

Write a "local config loader": read a JSON config file, with default value fallbacks.

Acceptance criteria

You can independently:

  • Distinguish the four APIs: dump/dumps/load/loads
  • Read and write JSON files
  • Handle parse failure scenarios

Common errors & debugging steps (beginner edition)

  • Can't understand the error: read the last line for the error type (e.g., TypeError, NameError), then trace back to the relevant code line.
  • Not sure about a variable's value: temporarily add print(variable, type(variable)) at key points to verify data matches expectations.
  • Code changes aren't taking effect: confirm the file is saved, you're running the right file, and your terminal environment (venv) is correct.

Common misconceptions

  • Misconception: JSON can use single quotes.
  • Reality: The JSON spec requires double quotes. Python dicts use single quotes, but JSON doesn't.