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 format for structured data. An API can return a JSON response containing named fields, nested objects, and arrays. In Python, distinguish the response text from the values you get after parsing it: `response.text` holds text, while `response.json()` returns Python data you can work with. 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 weather response has top-level fields such as `latitude` and nested objects such as `current`, which groups the reported time, temperature, and wind speed. section 22.2

Read an API result

A Chicago crime-data request uses a URL query to select a time range. Calling `result.json()` produces a Python list of records; each record has fields such as `date` and `primary_type`, Boolean fields such as `arrest`, and a nested `location` object. section 22.2

JSON-shaped data also appears in document storage, but the format matters. MongoDB stores documents as BSON, or binary JSON. Its documents resemble JSON objects or Python dictionaries, while examples include values such as dates and object IDs. Do not assume a MongoDB document is simply the JSON text returned by an API. section 23.7

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Shows raw and parsed API results, then distinguishes JSON-shaped documents from BSON; does not develop a JSON grammar.
Examples
Uses a weather response with nested measurements and a crime-data response parsed into a list of records.
What it assumes
Uses Python requests, dictionaries, and lists without teaching their fundamentals.
What you can do after
Apply it via requests to read API responses as Python data and recognize when MongoDB uses BSON instead.
How it connects
Connects JSON to HTTP GET requests, REST APIs, Python dictionaries and lists, MongoDB documents, and BSON.

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.