JSON parsing and API responses
JSON is the language of APIs. Every LLM response, every tool call, every config file is JSON. When you parse an AI response, you are converting a JSON string into a Python dictionary. Let us master this critical skill.
JSON Round-trip
How Python dicts become JSON and back
import json
# Python dict -> JSON string (dumps = dump string)
agent_config = {
"role": "SQL Expert",
"temperature": 0,
"tools": ["bash", "read_file"]
}
json_string = json.dumps(agent_config, indent=2)
print("Dict -> JSON string:")
print(json_string)
# JSON string -> Python dict (loads = load string)
api_response = '{"is_in_scope": true, "reason": "Question about orders"}'
parsed = json.loads(api_response)
print(f"In scope? {parsed['is_in_scope']}")
print(f"Reason: {parsed.get('reason', 'No reason')}")json.dumps() converts Python to JSON text. json.loads() converts JSON text back to Python. Note: JSON true becomes Python True, null becomes None.
The "s" stands for "string". json.dumps() returns a string. json.dump() writes directly to a file. Same for json.loads() (from string) vs json.load() (from file). You will use dumps/loads for API work and dump/load for file storage.
import json
# Parsing nested JSON (common in LLM responses)
llm_response = '''
{
"reasoning": "Using orders table with COUNT",
"sql_query": "SELECT COUNT(*) FROM orders WHERE order_status = 'delivered'"
}
'''
result = json.loads(llm_response)
sql = result.get("sql_query", "").strip()
print(f"Extracted SQL: {sql}")
# Reading/Writing JSON files
data = [
{"id": 1, "title": "Mushroom Burger", "price": 12.99},
{"id": 2, "title": "Quinoa Bowl", "price": 10.99},
]
with open("menu.json", "w") as f:
json.dump(data, f, indent=2) # dump to file
with open("menu.json", "r") as f:
loaded = json.load(f) # load from file
print(f"Loaded {len(loaded)} items")Real LLM responses often contain nested JSON. Use .get() for safe access and .strip() to clean whitespace.
Matching exercise: JSON functions
Loading practice…
Fill in the blanks: Parse an API response
Loading practice…
AI prompt: Try it with AI
Loading practice…
Validation checklist: JSON parsing checklist
Loading practice…