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¤t=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
