JSON Data Handling
Most APIs communicate using JSON. Agents send JSON in request bodies and receive JSON in responses. Handling JSON correctly is a core skill for API orchestration.
8 min•By Priygop Team•Updated 2026
JSON Parsing and Extraction
JSON Parsing and Extraction
import json
import requests
def extract_order_data(api_response: dict) -> dict:
"""
Extract only the fields the agent needs from an API response.
Agents should not receive raw full API responses — too much noise.
"""
try:
order = api_response.get("data", {}).get("order", {})
return {
"status": "success",
"order_id": order.get("id"),
"customer": order.get("customer", {}).get("email"),
"total": order.get("financials", {}).get("total"),
"order_status": order.get("status"),
"items_count": len(order.get("items", [])),
}
except (KeyError, TypeError) as e:
return {
"status": "error",
"error": f"Unexpected response format: {str(e)}"
}
# Simulated raw API response (deeply nested JSON)
raw_response = {
"data": {
"order": {
"id": "ORD-789",
"customer": {"email": "alice@example.com", "id": "C456"},
"status": "shipped",
"financials": {"subtotal": 80.00, "tax": 8.00, "total": 88.00},
"items": [{"sku": "P1", "qty": 1}, {"sku": "P2", "qty": 2}],
"created_at": "2024-01-15T10:00:00Z"
}
}
}
# The agent receives a clean, focused observation
agent_observation = extract_order_data(raw_response)
print(json.dumps(agent_observation, indent=2))