CSE Roadmap

Core tier · about 8 hours · 8 parts

Part 3 of 8 · 2 min read

JSON

The data format almost every API speaks, how it maps to Python, and what it cannot hold.

The body of a request or response is usually JSON.

JSON

A text format for data, built from a few pieces: objects ({} with named values), arrays ([] lists), strings (text in double quotes), numbers, true, false and null. Almost every web API speaks it.

JSON and Python line up closely:

JSON Python
object dict
array list
string str
number int or float
true / false True / False
null None
import json

text = '{"city": "Pune", "temperature_c": 31.5, "tags": ["warm", "humid"]}'
data = json.loads(text)          # text  -> Python objects
data["temperature_c"]            # 31.5
print(json.dumps(data, indent=2))    # Python objects -> text
{
  "city": "Pune",
  "temperature_c": 31.5,
  "tags": [
    "warm",
    "humid"
  ]
}

Remember the pair: loads reads text into Python, dumps writes Python out as text. (The s stands for string.)

JSON is strict. Python code that looks right can be invalid JSON:

>>> json.loads("{'a': 1}")
JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
>>> json.loads('{"a": 1,}')
JSONDecodeError: Illegal trailing comma before end of object: line 1 column 8 (char 7)

Keys must use double quotes, and a comma after the last item is not allowed. JSON also has no date type and no comments, and its keys are always text. Dates travel as strings, usually in the ISO 8601 form, such as 2026-10-23T14:30:00Z.

A model's reply is "JSON" only if you check it. Parse it with json.loads inside a try, then check its shape with a Pydantic model (Level 0, module 1). Never use eval on a model's reply: it would run whatever the text says.

Check yourself

  • What is the difference between json.loads and json.dumps?
  • Name two things that are fine in a Python dictionary but invalid in JSON.