Skip to content

JSONDecodeError: Expecting value

Cause: json.loads() was given text that does not start with a JSON value, usually a ```json fence, a line of prose, or an empty reply.

Copy-paste fix

Ask for JSON mode, check that the reply finished, then strip a code fence if one slipped through before parsing.

import json, re

FENCE = re.compile(r"^```(?:json)?\s*(.*?)\s*```$", re.S | re.I)

def parse_llm_json(raw):
    if raw is None or not raw.strip():
        raise ValueError("Empty model output: check finish_reason and refusals")
    text = raw.strip()
    m = FENCE.match(text)
    if m:
        text = m.group(1)
    return json.loads(text)

resp = client.chat.completions.create(
    model=MODEL,
    response_format={"type": "json_object"},
    messages=[{"role": "system", "content": "Reply with one JSON object only."},
              {"role": "user", "content": question}],
)
choice = resp.choices[0]
if choice.finish_reason == "length":
    raise RuntimeError("Reply was cut off at the token limit; JSON is incomplete")
data = parse_llm_json(choice.message.content)

Compare what a structured-output call costs across models on TokenCenter

What the error means

Expecting value is the message Python's json module raises when the first thing it reads is not a JSON value. With LLM output that is most often a Markdown code fence, a sentence before the JSON, or an empty string.

JSON mode (response_format={"type": "json_object"} in Chat Completions) makes the model return valid JSON. OpenAI's docs say you must also tell the model to produce JSON in a message, and that the content may be cut off when finish_reason is length.

Checklist

  1. Prefer Structured Outputs (a JSON Schema) where your model supports it; JSON mode only guarantees valid JSON, not your fields.
  2. Always include an explicit instruction to return JSON when JSON mode is on.
  3. Log the raw reply when parsing fails, so you can see what the model actually sent.
  4. Validate the parsed object against the fields your code needs.
  5. Set max output tokens high enough for your largest expected object.

Related

Sources

All guides · All errors