Skip to content
GitShowcase Forum

Structured JSON output from an LLM API still breaks my parser sometimes, what actually guarantees valid JSON?

Asked by Zainab Q. · AI APIs and LLM Integration2 repliesupdated

Short answer

We extract fields from customer documents with an LLM call and feed the result straight into a pipeline. The prompt says "Respond with only a JSON object matching this schema", and for most requests that works. In production a small fraction of responses still fail json.loads, and I have seen these failure shapes in logs:

Written by Zainab Q. ·
CiteGitShowcase Forum, "Structured JSON output from an LLM API still breaks my parser sometimes, what actually guarantees valid JSON?", https://gitshowcase.com/forum/discuss/structured-json-output-from-an-llm-api-still-breaks-my-parser/, accessed 2026-11-29.
  1. Member ·
    json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 412
    json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
    

    The second one is a response that starts with "Here is the JSON you asked for:" followed by a fenced block. The first looks like truncation.

    I have tried retrying once, stripping code fences with a regex, and lowering the temperature. It reduced the failures but did not remove them, and the retries add latency and cost.

    Is there a setting that actually guarantees valid JSON that matches my schema, or is defensive parsing just a fact of life? If there is a guarantee, what are its limits? I would like to know what can still go wrong before I rewrite the pipeline.

    0
    ReplyLink

Plain text or simple Markdown. Links are nofollow. Your email is never shown.

  1. Lex V.Member ·

    Honestly just make the prompt louder. "Return ONLY valid JSON, no prose, no markdown" in the system prompt plus a one shot example fixed it for me. If a model still adds prose after that I switch models.

  2. Teodor M.Member ·

    I keep a tiny repair step: strip fences, find the first { and last }, parse that. Ugly but it caught the "Here is the JSON" case for us. I would not rely on it for the truncated ones, since a repair there means guessing what the missing part was.

GitShowcase Forum. Questions and answers on shipping developer projects: dev tools, APIs, infrastructure and portfolios.