liveBook · Manning

Json.loads()

As explained in The Quick Python Book, Fourth Edition

json.loads() is a Python function that parses a JSON string or bytes object and returns the corresponding Python value.

json.loads() parses a JSON string or bytes representation and converts it into a Python value, commonly a dictionary when the JSON contains an object. section 22.3.1

Default JSON-to-Python conversions include:

  • object → dict; array → list; string → str. section 22.3.1
  • Integer and real numbers become int and float; true, false, and null become True, False, and None. section 22.3.1
  • Use json.load() instead when reading JSON from a file-like object. section 22.3.1

Parse an HTTP response

weather = json.loads(response.text)\ntemperature = weather['current']['temperature_2m']\n# 16.9\n\nWhen requests is used, response.json() performs the same conversion more directly. section 22.3.1

import json
import requests
response = requests.get("https://api.open-meteo.com/v1/forecast?latitude
=41.882&longitude=-87.623&current=temperature_2m,wind_speed_10m")
weather = json.loads(response.text)
weather
 
{'latitude': 41.879482,
 'longitude': -87.64975,
 'generationtime_ms': 0.025987625122070312,
 '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:15',
  'interval': 900,
  'temperature_2m': 16.9,
  'wind_speed_10m': 13.8}}
 
weather['current']['temperature_2m']
 
16.9

Inspect a complete parsed weather response and retrieve a nested temperature value. section 22.3.1

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains default type conversions and contrasts string parsing with file-based loading, without detailing decoder configuration.
Examples
Uses a weather API response, nested dictionary indexing, pretty printing, and newline-delimited weather records.
What it assumes
Assumes general Python knowledge, including dictionaries, indexing, files, and HTTP response objects.
What you can do after
Apply it via the json library to turn response text or individual JSON lines into usable Python values.
How it connects
Connects JSON with Python dictionaries, requests responses, json.load(), and the reverse serializers json.dump() and json.dumps().

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.