liveBook · Manning

JSON

As explained in The Quick Python Book, Fourth Edition

JSON is a text-based data interchange format that represents structured values using objects, arrays, strings, numbers, booleans, and null.

JSON is a text-based data interchange format for structured values. Objects contain key-value pairs; values can also be arrays, strings, numbers, booleans, or null. APIs can return JSON in response to HTTP requests. section 22.2 section 23.7

Weather response

A weather API response can contain nested objects, for example: {"current": {"temperature_2m": 16.9, "wind_speed_10m": 13.3}}. The outer object contains a current object, whose fields hold numeric measurements. section 22.2

response = requests.get("https://api.open-meteo.com/v1/forecast?
latitude=41.882&longitude=-87.623&current=temperature_2m,
wind_speed_10m")
weather = response.text
weather
 
{"latitude":41.879482,"longitude":-87.64975,"generationtime_ms":0.026941299
438476562,"utc_offset_seconds":0,"timezone":"GMT","timezone_abbreviation":
"GMT","elevation":185.0,"current_units":{"time":"iso8601","interval":
"seconds","temperature_2m":"°C","wind_speed_10m":"km/h"},"current":{"time":
"2024-09-02T02:00","interval":900,"temperature_2m":16.9,
"wind_speed_10m":13.3}}

The requests library fetches a weather API response; response.text exposes its JSON as text. section 22.2

To work with the decoded data instead of the response text, call response.json(). In the Chicago crime-data example, this produces a Python list of dictionaries. Python’s displayed values, such as True and False, are Python representations rather than JSON text. section 22.2

MongoDB documents provide a related storage example. They use BSON, or binary JSON, and consist of key-value pairs that resemble a JSON object or Python dictionary. section 23.7

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Shows response text and decoded Python data, but does not provide a full JSON syntax reference.
Examples
Uses weather and Chicago crime API responses to show JSON text and decoded data.
What you can do after
Apply it via Python requests to retrieve JSON text or decode an API response.
How it connects
Connects JSON with HTTP APIs, Python dictionaries, BSON, and MongoDB documents.

Also explained in

Compare how 35 books explain JSON →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.