LLM engineering · Medium · 15 min

Pull the JSON out of an LLM reply

You ask for JSON and the model answers with a sentence, a ```json block and sometimes stray braces. Extract the first valid object or return null.

Write extractJson(reply) that returns the first valid JSON object in reply, or null when there is none.

If there is a code block fenced with three backticks (with or without the json tag) and its content is a valid object, use it. Otherwise look at each { and its closing }, taking nested braces and braces inside strings such as "a}" into account, and try JSON.parse. If it fails, move on to the next {.

Only objects count: an array or a number is not a valid answer.

One more check uses LIVE: real output from your own Ollama if you switch on "My Ollama", or a different sample if not. That check looks at structure, not exact words.

Challenges 0/5

  • Reads the ```json block in REPLY
  • Finds the object inside plain prose
  • Respects braces inside strings
  • Returns null when there is no valid object
  • Reads the real reply from your model (My Ollama) or another sample

function extractJson(reply) {
  // 1. try a fenced code block first
  // 2. otherwise scan every '{', find its matching '}' (strings may contain braces)
  // 3. JSON.parse the slice; return the first plain object, or null
  try {
    return JSON.parse(reply);
  } catch (e) {
    return null;
  }
}

console.log(extractJson(REPLY));

Tab indents, Ctrl+Z undoes. To leave the editor with the keyboard: Esc, then Tab.

Console output appears here (console.log).

Why this matters

Asking for JSON does not guarantee you get only JSON. A small model adds a polite sentence, wraps the answer in a code block or leaves a stray brace, and your JSON.parse fails on the first odd invoice. Pulling out the first valid object is the safety net under any data extraction, classification or tool call. The other half of the answer is asking the server for output that follows a schema. What that fixes and what it does not is in Ollama structured output with a JSON schema: 40 invoices measured.

Go deeper: the Ollama reference →

This in production, with your data? Let's talk for 15 minutes →