Learning Language Mode:English (Global Tech)

Switch anytime between English and Roman Urdu without losing your spot.

Coding & Logic FundamentalsLevel: INTERMEDIATE

Data Structures & JSON Schemas for AI APIs

Understand lists, dictionaries, nested JSON schemas, and Pydantic validation. Learn how to force AI models to output strict, parseable JSON rather than unpredictable conversational text.

9 min readUpdated: 2026-10-15

Structured JSON Schemas for AI Integration

When your application communicates with an AI agent, you do not want conversational text like "Sure, here are your recommendations...". You want a structured machine-readable JSON payload.

Schema Blueprint Example

``json { "doctorName": "Dr. Sarah Ahmed", "specialty": "Cardiology", "availableSlots": ["10:00 AM", "02:30 PM", "04:15 PM"], "consultationFeeUSD": 50 } ``

Python Structured Gemini Call with Strict JSON Output

pythonPython Structured Gemini Call with Strict JSON Output
from google import genai
from pydantic import BaseModel

class ClinicSlot(BaseModel):
    doctor_name: str
    specialty: str
    available_times: list[str]

client = genai.Client()

response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="Generate mock appointment schedule for a clinic.",
    config={"response_mime_type": "application/json", "response_schema": ClinicSlot},
)

print(response.text)

Expected Output: Guaranteed structured JSON response conforming 100% to the Pydantic schema.

Key Takeaways

  • JSON (JavaScript Object Notation) is the universal data exchange standard between web apps and AI models.
  • Enforcing a JSON schema ensures the model returns exact keys with correct data types.
  • Dictionaries / Objects map key-value pairs; Arrays / Lists store ordered sequences.
  • Always wrap JSON.parse() or json.loads() in try/catch blocks to gracefully handle network anomalies.

Common Pitfalls to Avoid

  • Asking the AI for JSON without providing an explicit schema, resulting in markdown code block wrappers (```json ... ```) that break parsers.
  • Assuming numbers returned as strings ('$50') will mathematically add up without parsing.

Frequently Asked Questions

How do I make Gemini output strict JSON?

Set config = {'response_mime_type': 'application/json', 'response_schema': YourPydanticModel} in the generate_content call.

Was this tutorial helpful?

Your feedback helps us continuously improve our AI engineering curricula.

Continue Learning

Expand your skills with these recommended follow-up guides.