JSON Mode Prompt Schema Output in Python
Extract a user object to JSON with explicit schema keys, ready for LLM JSON-mode prompts.
Python code
20 linesimport json
from typing import Any, Dict
def extract_user_as_json(user: Dict[str, Any]) -> str:
"""Extract a user object and return it as JSON using explicit schema keys."""
schema_fields = ("id", "name", "email", "is_active")
user_subset = {key: user[key] for key in schema_fields if key in user}
return json.dumps(user_subset, indent=2)
if __name__ == "__main__":
sample_user = {
"id": 42,
"name": "Alice Johnson",
"email": "alice@example.com",
"is_active": True,
"unused_field": "ignored",
}
print(extract_user_as_json(sample_user))
Output
{
"id": 42,
"name": "Alice Johnson",
"email": "alice@example.com",
"is_active": true
}
How it works
This function filters a user dict against a fixed tuple of schema fields, ignoring extras like unused_field, producing a clean JSON subset. json.dumps with indent=2 formats the output for readability in logs or LLM prompts. Using a tuple for schema_fields keeps the allowed keys explicit and immutable, which makes the contract easy to audit. The function returns a string, which is the standard input format for JSON-mode prompts on LLM APIs.
Common mistakes
- Assuming all keys exist without checking `if key in user`
- Including extra fields that break strict JSON schemas
- Returning a dict instead of a JSON string for API calls
Variations
- Add type validation with pydantic for stricter schema enforcement
- Use `json.dumps(..., sort_keys=True)` for deterministic ordering
Real-world use cases
- Preparing structured user data for LLM JSON-mode completions in chat assistants.
- Filtering database records to match an API's expected response schema.
- Sanitizing webhook payloads before sending them to an AI summarization service.
Sponsored
More from AI & LLM integration patterns
- Cache LLM Completions by Hashing the Prompt in Python easy
- Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo easy
- Circuit Breaker Pattern in Python for LLM API Calls medium
- Cosine Similarity to Retrieve Top K Chunks in Python easy
- Demonstrate Prompt Injection Bypass in Python easy
- How to Accumulate Streamed Tokens into a Final String in Python easy
Keep learning
Related tutorials and quizzes for this topic.