JSON Mode Prompt Schema Output in Python

Extract a user object to JSON with explicit schema keys, ready for LLM JSON-mode prompts.

Easy Python 3.9+ Aug 9, 2026 AI & LLM integration patterns 13 views 0 copies

Python code

20 lines
Python 3.9+
import 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

stdout
{
  "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

  1. Add type validation with pydantic for stricter schema enforcement
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from AI & LLM integration patterns

Related tutorials and quizzes for this topic.