Back to Tutorials
Prompt Engineering
Intermediate

Reliable JSON from an LLM: Four Ways to Ask

A real model turns café orders into JSON four ways, from a plain request to constrained decoding. Your browser parses every answer: valid is easy, right is not.

9 minInteractive: drag, click and try things as you read


The moment a program, not a person, reads a language model’s answer, the answer has to be in a strict format, and that format is almost always JSON. Models are happy to oblige, with a friendly “Here’s the JSON:” in front, Markdown fences around it, and field names of their own choosing, and any of those breaks the program. Here a real model turns café orders into JSON four different ways, and your browser parses every answer. Valid JSON is a solved problem; right JSON is not.

Just asking for JSON#

Bean There, a made-up café, gets catering orders by message: “Two dozen cinnamon buns please, I’ll pick them up tomorrow morning.” Its booking system needs each one as a name, a list of items with quantities, a date and whether to deliver. The simplest approach is to paste the message into a prompt and add “Extract the order from this message as JSON.”

Predict first

With that plain request, how many of the 30 answers can a program read as JSON exactly as they come back?

Try it
The orders are made up. The answers are real: Qwen3-1.7B, a small open model, run offline with greedy decoding, shown exactly as it wrote them. Your browser runs JSON.parse on each one, checks the fields and types, and compares the values with what the message asked for.

Turn on the repair and all 30 plain answers parse, and all 30 are still useless to the program, because the field names are invented. Spelling out the schema fixes both problems at once: all 30 answers parse as they are, with exactly the fields and types we asked for. Then look at the values. Only 8 of the 30 orders are right in every field. All 17 wrong dates are the same date, today’s, even when the message says “20 October” or “Friday 30 October”, and the four messages that give no date get today’s date too, because the schema demands one. All 11 delivery mistakes are the same mistake: a customer collecting the order, marked for delivery.

Four ways to ask#

  1. Just ask. “As JSON”, and nothing else.
  2. Spell out the schema. Name every field and its type, and say “Return ONLY valid JSON, no markdown, no commentary.”
  3. Start the answer for it. With a model you run yourself, you can write the first characters of its reply, and some APIs allow it too. Start it with { and there is no room for a friendly preamble.
  4. Constrained decoding. At every step, the software removes from the model’s choices any token that would break the schema, so the answer can only be valid JSON with your fields and types. Hosted APIs offer this as a structured-output or JSON mode; locally, tools such as Ollama and llama.cpp support it, and libraries like lm-format-enforcer (used here) add it to Hugging Face models.
Try it
The same 30 orders, all four ways, with no repair. Computed in your browser from the answers above.

For this model, a precise prompt was already enough to get valid JSON every time, so constrained decoding had nothing left to fix: its 30 answers were word for word the same as the precise prompt’s, 8 of them right. With longer schemas, other models or a sloppier prompt, it’s the safety net that makes a parse failure impossible, so use it when your API offers it. Starting the answer with { got 11 right, the best of the four, but three more right answers out of 30 is not a difference to build on. None of the four can stop the model misreading the order. That takes checking the values, which is where validation comes in.

In code#

Starting the answer with {, plus the repair as a fallback, with the same small model, free and local (pip install transformers torch). Both answers parse, and both dates are wrong: today’s date instead of tomorrow and 20 October.

import json, re
from transformers import AutoModelForCausalLM, AutoTokenizer

name = "Qwen/Qwen3-1.7B"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name)

SCHEMA = '{"name": string, "items": [{"item": string, "quantity": integer}], "date": "YYYY-MM-DD", "delivery": boolean}'

def extract(message):
    messages = [
        {"role": "system", "content": "You take catering orders for Bean There, a café. Today is Saturday 10 October 2026."},
        {"role": "user", "content": f"Extract the order from this message. Return ONLY valid JSON matching this schema, "
                                    f"with no markdown and no commentary:\n{SCHEMA}\n\nMessage: {message}"},
    ]
    prompt = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True, enable_thinking=False)
    prompt += "{"  # start the answer for the model, so it can't open with chatter
    inputs = tok(prompt, return_tensors="pt")
    out = model.generate(**inputs, max_new_tokens=150, do_sample=False)
    text = "{" + tok.decode(out[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
    try:
        return json.loads(text)
    except json.JSONDecodeError:
        match = re.search(r"\{.*\}", text, re.S)  # repair: keep only the outermost braces
        return json.loads(match.group(0))

for message in ["Tom Reed here. Two dozen cinnamon buns please, I'll pick them up tomorrow morning.",
                "Order from Sam Patel: 8 lattes, 4 flat whites. Deliver to the library, 20 October."]:
    print(json.dumps(extract(message)))
# {"name": "Tom Reed", "items": [{"item": "cinnamon buns", "quantity": 24}], "date": "2026-10-10", "delivery": false}
# {"name": "Sam Patel", "items": [{"item": "latte", "quantity": 8}, {"item": "flat white", "quantity": 4}], "date": "2026-10-10", "delivery": true}

What to remember

  • Asked plainly, a model wraps its JSON in chatter and fences and picks its own field names, so programs choke on it.
  • Spelling out the schema got valid JSON with the right fields 30 times out of 30 here; constrained decoding makes that a guarantee rather than a hope.
  • Valid JSON can still be wrong: check the values too, with a schema validator and business rules, before you act on them.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.