KING BON
← Journal

·3 min read

Getting reliable JSON out of an LLM

Asking a model nicely for JSON works most of the time. Here is how to make it work every time: schemas, validation, confidence and a fallback.

AI / LLMs / Automation

The most useful thing an LLM does in a business app usually isn’t chatting. It’s reading messy input, like an email, a PDF or a support ticket, and turning it into clean fields your code can use. An invoice email becomes { vendor, amount, due_date }. A ticket becomes { category, urgency }.

“Most of the time” isn’t good enough when the output goes into a database. These are the layers I use to make it dependable.

1. Constrain the output with a schema

Don’t just write “respond in JSON” in the prompt. Most model APIs and local runtimes can force output to match a JSON Schema. With Ollama, for example, you pass the schema as format:

const schema = {
  type: 'object',
  properties: {
    intent: { type: 'string', enum: ['invoice', 'support', 'other'] },
    confidence: { type: 'number' },
    vendor: { type: ['string', 'null'] },
    amount: { type: ['number', 'null'] },
    due_date: { type: ['string', 'null'], description: 'YYYY-MM-DD' },
  },
  required: ['intent', 'confidence', 'vendor', 'amount', 'due_date'],
};

const res = await fetch('http://localhost:11434/api/chat', {
  method: 'POST',
  body: JSON.stringify({
    model: 'llama3.1:8b',
    stream: false,
    format: schema,
    options: { temperature: 0 },
    messages: [
      { role: 'system', content: 'Extract fields from the email. Use null when a field is not present. Never guess.' },
      { role: 'user', content: emailText },
    ],
  }),
});

An enum for categories stops the model from inventing new ones. Allowing null gives it a legitimate way to say “not there” instead of making something up.

2. Validate anyway

A schema guarantees the shape, not the sense. Validate in your own code too, with Zod, Laravel’s validator or plain checks: is the amount positive, is the date real, is it in the future?

const Invoice = z.object({
  intent: z.enum(['invoice', 'support', 'other']),
  confidence: z.number().min(0).max(1),
  amount: z.number().positive().nullable(),
  due_date: z.string().date().nullable(),
});
const parsed = Invoice.safeParse(JSON.parse(res.message.content));

3. Ask for confidence, and use it

Having the model rate its own confidence isn’t perfectly calibrated, but it’s a useful signal. Combine it with your validation results:

  • Valid and confident: process automatically.
  • Valid but uncertain, or a required field is null: send to a person.
  • Invalid: retry once with the error message included, then send to a person.

4. Keep the original

Store the raw input next to the extracted fields. When something looks wrong, you can see exactly what the model saw, and you have real examples to improve your prompt with.

5. Test with real, ugly input

Build a small set of real examples, including the awkward ones: forwarded threads, two invoices in one email, amounts written in words. Run them every time you change the prompt or the model. It’s the cheapest insurance there is.

With these layers, the model becomes one dependable step in a pipeline instead of the part you’re nervous about.