Skip to content

JSON API CONSUMPTION - Working with JSON responses

Python
#!/usr/bin/env python3
"""JSON API CONSUMPTION - Working with JSON responses"""
import urllib.request
import json
print("JSON API Consumption:")
url = "http://httpbin.org/json"
try:
    with urllib.request.urlopen(url) as response:
        data = response.read()
        json_data = json.loads(data)
        print(f"  Loaded JSON object")
        print(f"  Type: {type(json_data)}")
        if isinstance(json_data, dict):
            print(f"  Keys: {list(json_data.keys())[:5]}")
except Exception as e:
    print(f"  Error: {e}")