DEV Community

Cover image for \"Reply in JSON\" Failed 20/20: Getting Reliable JSON From an LLM
Muiduzzaman Lipu for Refactorly

Posted on

\"Reply in JSON\" Failed 20/20: Getting Reliable JSON From an LLM

I asked a local LLM to extract data from a support email and "reply in JSON", 20 times. json.loads succeeded zero times. Then I changed one parameter and got 20 out of 20. But even perfect JSON turned out to be wrong data in one case. Here's every step, with real results.

Setup: llama3.2:3b running locally in Ollama, the ollama Python library (0.6) and Pydantic 2, temperature 0.8, 20 runs per test.

Video version:

The prompt everyone writes

import json, ollama

EMAIL = """Hi, this is Maria Lopez. My order #A-1042 arrived broken.
I paid $49.90 and I'd like a refund please. Pretty disappointed."""

prompt = f"""Extract the customer name, order id, refund amount and sentiment from this email.
Reply in JSON.

{EMAIL}"""

r = ollama.chat(model="llama3.2:3b", messages=[{"role": "user", "content": prompt}])
data = json.loads(r.message.content)
Enter fullscreen mode Exit fullscreen mode

Result over 20 runs: parsed 0, failed 20. Every answer looked like this:

Here is the extracted data in JSON format:

```
{
  "customerName": "Maria Lopez",
  "orderId": "A-1042",
  "refundAmount": 49.90,
  "sentiment": "negative"
}
```
Enter fullscreen mode Exit fullscreen mode

json.loads fails on the first character: JSONDecodeError: Expecting value: line 1 column 1 (char 0).

"Just cut it out with a regex"

m = re.search(r"\{.*\}", text, re.S)
data = json.loads(m.group(0))
Enter fullscreen mode Exit fullscreen mode

Now all 20 parse. But look at the data:

  • Keys: customer_name ×14, customerName ×5, orderID ×1.
  • Amount: a number 17 times, a string (like "$49.90") 3 times.
  • Sentiment: negative ×10, Negative ×9, disappointed ×1.

Your code would need to handle every variant.

The fix: structured output (a schema)

from typing import Literal
from pydantic import BaseModel

class Refund(BaseModel):
    customer_name: str
    order_id: str
    amount: float
    sentiment: Literal["positive", "neutral", "negative"]

r = ollama.chat(
    model="llama3.2:3b",
    messages=[{"role": "user", "content": f"Extract the refund request.\n\n{EMAIL}"}],
    format=Refund.model_json_schema(),
)
refund = Refund.model_validate_json(r.message.content)
Enter fullscreen mode Exit fullscreen mode

With a JSON schema as the format, the model's output is constrained to that schema: no intro sentence, no code fences, exact keys, real numbers, and only the allowed enum values.

Result: 20/20 valid, and all 20 identical:

{"customer_name": "Maria Lopez", "order_id": "A-1042", "amount": 49.9, "sentiment": "negative"}
Enter fullscreen mode Exit fullscreen mode

Hosted APIs (OpenAI, Gemini, Claude) offer the same idea, usually called structured outputs. Check your provider's docs for the exact parameter.

The trap: valid JSON, wrong data

I removed the price from the email:

EMAIL2 = """Hi, this is Maria Lopez. My order #A-1042 arrived broken.
I'd like a refund please."""
Enter fullscreen mode Exit fullscreen mode

With amount: float (required), the model has to write a number. In 20/20 runs it wrote 0.0. That's valid JSON and passes the schema, and it means a zero-dollar refund.

Make the field optional and say so in the prompt:

class Refund(BaseModel):
    customer_name: str
    order_id: str
    amount: float | None = None
    sentiment: Literal["positive", "neutral", "negative"]

# prompt: "Extract the refund request. Use null for anything the email doesn't say."
Enter fullscreen mode Exit fullscreen mode

Result: amount: null in 20/20 runs.

Validate the meaning, not just the shape

from pydantic import Field

class Refund(BaseModel):
    customer_name: str
    order_id: str = Field(pattern=r"^A-\d+$")
    amount: float | None = Field(None, gt=0)
    sentiment: Literal["positive", "neutral", "negative"]
Enter fullscreen mode Exit fullscreen mode

Now a 0.0 amount raises:

1 validation error for Refund
amount
  Input should be greater than 0 [type=greater_than, input_value=0.0, input_type=float]
Enter fullscreen mode Exit fullscreen mode

Catch the ValidationError and route the request to a human instead of acting on it.

Cheat sheet

  • "Reply in JSON" is a wish, not a contract.
  • Regex extraction parses, but the data is inconsistent.
  • Pass a schema: format=Model.model_json_schema() (or your API's structured-output option).
  • Use Literal[...] / enums for fixed choices.
  • Optional fields + "use null" stop the model from inventing values.
  • Validate meaning too: Field(gt=0), patterns, business rules.

How do you parse AI output today? 👇


I post one tested coding tip every day on YouTube at Refactorly. The 30-second version of this one is here.

Top comments (1)

Collapse
 
ahmetozel profile image
Ahmet Özel •

Demonstrating a 0-of-20 parse rate with plain "Reply in JSON" prompting—and then exposing key-name drift (customer_name vs customerName), string-vs-float amounts, and enum casing variance even after regex extraction—makes the case for grammar-constrained structured outputs undeniable. Passing Pydantic's model_json_schema() straight into Ollama's format parameter jumps reliability to 20/20 identical parses immediately.

That final missing-price trap is the crucial reminder every production pipeline needs: schema enforcement guarantees valid JSON syntax and types, not factual grounding. Making fields Optional[float] and explicitly instructing null on missing values prevents constrained decoding from fabricating 0.0 or hallucinated totals.