Why AI & APIs Use JSON (and Handling JSON Errors)
In this lesson, you will learn how modern AI models like ChatGPT and Google Gemini use JSON, and how to protect your code from crashing when an API returns invalid JSON.
1. How AI Models Use JSON: Structured Outputs
When you build an AI application (e.g., an automated resume parser or email classifier), you don't want the AI to reply with long conversational paragraphs like "Sure! Here is the summary...".
Instead, you instruct the AI to respond strictly in JSON:
import json
# Simulated response from an AI classification model:
ai_response_text = """
{
"sender": "hdfcbank@alerts.com",
"category": "Transaction Alert",
"amount": 2500.00,
"is_fraud_suspected": false
}
"""
parsed_data = json.loads(ai_response_text)
if parsed_data["amount"] > 1000:
print(f"🔔 High value transaction alert: ₹{parsed_data['amount']}")
2. Handling Corrupted / Malformed JSON Safely
In the real world, network drops or AI "hallucinations" can result in broken, incomplete JSON text (e.g., missing closing quotes or broken brackets).
If you pass invalid text to json.loads(), Python raises a json.JSONDecodeError:
import json
corrupted_json_text = '{"name": "Sai", "score": 95' # ❌ Missing closing brace!
try:
data = json.loads(corrupted_json_text)
print("User score:", data["score"])
except json.JSONDecodeError as error:
print("🚨 Could not parse JSON data!")
print(f"Error details: {error}")
Output:
🚨 Could not parse JSON data!
Error details: Expecting ',' delimiter: line 1 column 27 (char 26)
Whenever your Python application reads JSON from a web server, external file, or user input, always wrap json.loads() or json.load() in a try-except json.JSONDecodeError block to prevent crashes.
Quick Summary
- Structured LLM Outputs: Modern AI models (OpenAI, Gemini, Anthropic) return structured function calls and analytical data in JSON.
- Schema Enforcement: Strict JSON keys allow downstream Python systems to reliably automate business workflows.
- Defensive Parsing: Always wrap JSON parsing in
try ... except json.JSONDecodeErrorto handle malformed outputs or network truncations safely.
What's Next?
Now that you can exchange data using JSON, let's learn how to organize code into reusable files and manage external libraries in Module 16: Modules & Packages!