Serialize and Format Data for LLM Prompts in Python

Use dataclasses and the json module to convert Python objects to JSON strings, parse them back, and format structured data into prompt-friendly text for LLM calls.

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

Python code

42 lines
Python 3.9+
import json
from dataclasses import dataclass, asdict


@dataclass
class Recipe:
    """Simple data model to represent a recipe."""
    name: str
    cuisine: str
    prep_minutes: int


def to_json(recipe: Recipe) -> str:
    """Serialize a Recipe to a JSON string."""
    return json.dumps(asdict(recipe), indent=2)


def from_json(json_str: str) -> Recipe:
    """Deserialize a JSON string into a Recipe."""
    data = json.loads(json_str)
    return Recipe(**data)


def format_for_llm(recipe: Recipe) -> str:
    """Format the recipe into a prompt-friendly string."""
    return (
        f"Recipe: {recipe.name}\n"
        f"Cuisine: {recipe.cuisine}\n"
        f"Prep time: {recipe.prep_minutes} minutes"
    )


if __name__ == "__main__":
    recipe = Recipe("Spaghetti Carbonara", "Italian", 30)
    json_data = to_json(recipe)
    print("Serialized JSON:")
    print(json_data)
    print("\nDeserialized object:")
    recreated = from_json(json_data)
    print(recreated)
    print("\nLLM-ready format:")
    print(format_for_llm(recreated))

Output

stdout
Serialized JSON:
{
  "name": "Spaghetti Carbonara",
  "cuisine": "Italian",
  "prep_minutes": 30
}

Deserialized object:
Recipe(name='Spaghetti Carbonara', cuisine='Italian', prep_minutes=30)

LLM-ready format:
Recipe: Spaghetti Carbonara
Cuisine: Italian
Prep time: 30 minutes

How it works

The @dataclass decorator automatically generates an __init__ method and other dunder methods, so you don't have to write boilerplate for the Recipe class. asdict(recipe) converts the dataclass instance into a plain dictionary, which json.dumps can serialize to a JSON string with proper indentation. On the way back, json.loads parses the JSON into a dictionary, and the **data unpacking syntax passes those fields as keyword arguments to the Recipe constructor. The format_for_llm function produces a simple, consistent text representation that makes structured data easy for an LLM to consume in a prompt.

Common mistakes

  • Forgetting to import `asdict` from `dataclasses` — you need it to convert the dataclass to a dict before serializing.
  • Calling `json.dumps(recipe)` directly on the dataclass, which raises a `TypeError` because dataclasses aren't JSON-serializable by default.
  • Assuming the JSON string always matches the dataclass fields exactly — missing or extra keys will cause a `TypeError` on deserialization.

Variations

  1. Use `json.dumps(recipe.__dict__)` instead of `asdict(recipe)` for a simple dataclass, though `asdict` is safer for nested structures.
  2. Add a custom `to_dict` method to the dataclass if you need to rename or transform fields before serialization.

Real-world use cases

  • Converting database records into JSON payloads before sending them to an LLM API for summarization or classification.
  • Building prompt templates that inject structured data like user profiles or product details into a consistent, readable format.
  • Storing LLM-generated content in JSON format and parsing it back into typed Python objects for further processing.

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.