AI Wiki中文/EN

Structured output: valid JSON can still be the wrong answer

结构化输出

Validate an invoice through parsing, field rules, exact arithmetic and source evidence.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The invoice adds up, but the price was invented

A source catalogue says a notebook costs 3.50 USD. An extracted record says quantity 2, unit price 4.00, total 8.00. Its JSON parses. Its field types and ranges can satisfy a schema. Its arithmetic is correct. It still disagrees with the source.

Structured output is a machine-readable response governed by an explicit contract. The contract might use JSON Schema, a grammar or a fixed record type. Its purpose is to make downstream interpretation predictable. It does not by itself prove that the data are true. JSONSchemaBench, section 5, distinguishes a framework accepting a schema, producing compliant outputs in observed runs, and truly implementing the schema’s full semantics. Those are separate claims even before factual accuracy is considered.

Our application is a small invoice extraction pipeline. A non-AI baseline reads an already structured source record directly. If the source is free text, a model may propose a record, but the caller must still decide whether to accept it. The local example validates authored candidate strings; it does not call or simulate an extraction model.

Parsing, field rules, arithmetic and evidence reject different invoice errors.
Parsing, field rules, arithmetic and evidence reject different invoice errors.

Use several checks with different jobs

Let P be the set accepted by the ingestion parser, S the schema-compliant records, R the records satisfying cross-field arithmetic, and E those supported by the source catalogue. The accepted set is their intersection:

A=P∩S∩R∩E.\mathcal A=\mathcal P\cap\mathcal S\cap\mathcal R\cap\mathcal E.

The pipeline stops at the first failed layer. P here includes our explicit resource and interoperability policy, not just the JSON grammar. RFC 8259, section 4, recommends unique object names and explains that implementations differ on duplicates. Our application rejects duplicates rather than silently keeping the last value. That is a stricter ingestion choice, not a claim that the JSON grammar universally forbids them.

The schema requires item, quantity, unit price, total and currency. Quantity must be an integer from 1 through 10; prices and totals have finite nonnegative bounds. Currency must be one of two allowed strings. Every required key must exist, and extra keys are forbidden. JSON Schema Validation, sections 6.1.1–6.1.2 and 6.5.3, defines type, enumeration and required properties. Core, section 10.3.2.3, defines additionalProperties in relation to the property rules in the same schema object.

Do not confuse JSON’s numeric integer semantics with a programming language’s type hierarchy. The schema’s integer type accepts a number with zero fractional part, including 3.0. A JSON boolean is not a number; Python’s True being an int subclass must not make it a valid quantity.

Next check the arithmetic contract:

t=q u,q∈{1,…,10},0≤u≤104,0≤t≤105.t=q\,u,\qquad q\in\{1,\ldots,10\},\quad 0\le u\le10^4,\quad 0\le t\le10^5.

In this equation q is quantity, u is unit price and t is total. These bounds alone do not impose the equality. The program performs it separately using exact rational arithmetic. It then checks the item’s existence, the exact source price and the source currency,USD. The schema permitsEUR to illustrate that the general record format can be broader than this particular source’s evidence.

A schema keyword also needs the intended validator behavior. Validation sections 7.2.1–7.2.2 distinguish format annotation from format assertion. A format label does not automatically establish that every tool has performed a full check. Even a syntactically valid address would not prove that its recipient exists. This invoice example uses no format keyword and claims no general-purpose schema implementation.

Pass rates need explicit denominators. The chain rule expresses final acceptance without assuming that the layers are independent:

P(A)=P(P)P(S∣P)P(R∣P,S)P(E∣P,S,R).P(A)=P(P)P(S\mid P)P(R\mid P,S)P(E\mid P,S,R).

For our 14 authored strings, 11 pass ingestion, 6 pass the schema, 5 pass arithmetic and 2 pass source evidence. Thus the successive rates are 11/14,6/11,5/6 and 2/5; their product is 2/14. These are counts on a test fixture, not estimated production failure rates. Returning only “all accepted JSON was valid” would hide the rejection rate and the other layers.

Validate candidates before handing them onward

Run the complete program with Python 3.12; it uses only the standard library. SCHEMA documents the single invoice contract. schema_valid implements just that contract by hand, not arbitrary JSON Schema. The local source catalogue is also authored.

The ingestion profile limits UTF-8 input to 4,096 bytes, container depth to 16, decimal significands to 256 digits and the absolute decimal exponent to 256. These application limits are narrower than JSON’s syntax. The parser refuses non-JSON constants such asNaN and rejects duplicate keys. It first parses a byte-bounded string, then checks depth iteratively.

"""Bounded JSON ingestion and a single authored invoice contract; not a general schema engine."""
from decimal import Decimal,InvalidOperation
from fractions import Fraction
import json

CATALOG={'notebook':Decimal('3.50'),'clip':Decimal('0.10')}
KEYS={'item','quantity','unit_price','total','currency'}
SCHEMA={'$schema':'https://json-schema.org/draft/2020-12/schema','type':'object','required':sorted(KEYS),'additionalProperties':False,'properties':{
 'item':{'type':'string','minLength':1},'quantity':{'type':'integer','minimum':1,'maximum':10},
 'unit_price':{'type':'number','minimum':0,'maximum':10000},'total':{'type':'number','minimum':0,'maximum':100000},'currency':{'enum':['USD','EUR']}}}


def parse(text):
    if not isinstance(text,str) or len(text.encode('utf-8'))>4096:raise ValueError('JSON text limited to4096 UTF-8 bytes')
    def pairs(items):
        result={}
        for key,value in items:
            if key in result:raise ValueError('duplicate object name')
            result[key]=value
        return result
    def decimal_value(value):
        try:result=Decimal(value)
        except InvalidOperation as exc:raise ValueError('unrepresentable decimal') from exc
        if len(result.as_tuple().digits)>256 or abs(result.as_tuple().exponent)>256:
            raise ValueError('decimal precision or exponent outside ingestion profile')
        return result
    def forbidden(value):raise ValueError('non-JSON numeric constant')
    try:result=json.loads(text,parse_float=decimal_value,parse_constant=forbidden,object_pairs_hook=pairs)
    except (json.JSONDecodeError,RecursionError) as exc:raise ValueError('invalid or over-nested JSON') from exc
    stack=[(result,1)]
    while stack:
        value,depth=stack.pop()
        if isinstance(value,(dict,list)):
            if depth>16:raise ValueError('container depth limited to16')
            children=value.values() if isinstance(value,dict) else value
            stack.extend((child,depth+1) for child in children)
    return result


def number(value):
    return type(value) is int or isinstance(value,Decimal) and value.is_finite()


def schema_valid(obj):
    if not isinstance(obj,dict) or set(obj)!=KEYS:return False
    if not isinstance(obj['item'],str) or not obj['item'] or obj['currency'] not in ['USD','EUR']:return False
    q=obj['quantity']
    if not number(q) or not 1<=q<=10 or q!=int(q):return False
    return all(number(obj[k]) and 0<=obj[k]<=limit for k,limit in [('unit_price',10000),('total',100000)])


def inspect(text):
    try:obj=parse(text)
    except ValueError:return dict(parse=False,schema=False,arithmetic=False,evidence=False)
    schema=schema_valid(obj)
    arithmetic=schema and Fraction(obj['quantity'])*Fraction(obj['unit_price'])==Fraction(obj['total'])
    evidence=arithmetic and obj['item'] in CATALOG and Decimal(obj['unit_price'])==CATALOG[obj['item']] and obj['currency']=='USD'
    return dict(parse=True,schema=bool(schema),arithmetic=bool(arithmetic),evidence=bool(evidence))


def bounded_retry(candidates,limit=2):
    if type(limit) is not int or not 1<=limit<=5:raise ValueError('retry budget1..5 required')
    if not isinstance(candidates,(list,tuple)):raise ValueError('finite candidate list required')
    attempts=[]
    for candidate in candidates[:limit]:
        result=inspect(candidate);attempts.append(result)
        if result['evidence']:return dict(accepted=True,attempts=len(attempts),checks=attempts)
    return dict(accepted=False,attempts=len(attempts),checks=attempts)


def demo():
    good='{"item":"notebook","quantity":2,"unit_price":3.50,"total":7.00,"currency":"USD"}'
    cases={'valid':good,'syntax':good[:-1]+',}','duplicate':good[:-1]+',"quantity":1}',
      'nan':good.replace('3.50','NaN'),'missing':good.replace(',"currency":"USD"',''),
      'extra':good[:-1]+',"approved":true}','boolean':good.replace('"quantity":2','"quantity":true'),
      'fraction':good.replace('"quantity":2','"quantity":2.5'),'wrong_total':good.replace('7.00','7.01'),
      'wrong_currency':good.replace('USD','GBP'),'unknown_item':good.replace('notebook','pencil'),
      'wrong_price':good.replace('3.50','4.00').replace('7.00','8.00'),
      'exact_decimal':'{"item":"clip","quantity":3.0,"unit_price":0.10,"total":0.30,"currency":"USD"}',
      'unsupported_evidence_currency':good.replace('USD','EUR')}
    results={k:inspect(v) for k,v in cases.items()};counts={k:sum(v[k] for v in results.values()) for k in ['parse','schema','arithmetic','evidence']}
    return dict(cases=cases,results=results,counts=counts,total_cases=len(cases),retry_success=bounded_retry([cases['syntax'],good]),retry_exhausted=bounded_retry([cases['syntax'],cases['wrong_total'],good]),schema=SCHEMA)

if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))

A decimal is parsed from its source spelling, then converted to Fraction for multiplication. That avoids binary floating-point surprises and the default 28-digit rounding context of Decimal arithmetic. For example, 3 times 0.10 equals 0.30 exactly. A quantity written as 3.0 is accepted; a quantity written as true or 2.5 is rejected.

The fixture distinguishes malformed syntax, duplicate keys, missing fields, extra fields, type errors, arithmetic errors and unsupported facts. wrong_price is arithmetically consistent yet fails evidence; unknown_item fails because the catalogue lacks the item. No downstream action occurs when a record fails.

For a bounded input of length L, parsing and traversal are O(L) structural work, with at most O(L) stored content. Exact numeric operations also depend on operand digit length; the significand and exponent bounds keep that cost bounded here. A general schema with references or complex combinations needs its own resource analysis and validator tests.

Retry limits are part of the interface

Return a clear failure state when validation fails. A caller may request a corrected candidate, fall back to a deterministic parser, or ask for review. The program only consumes a provided list of candidate strings. Its default budget is two attempts; a valid third candidate is deliberately not inspected after the budget is exhausted.

For an illustrative model with independent attempts of identical success probability p, a budget B has the following success chance and expected number of attempted calls:

P(success by B)=1−(1−p)B,E[NB]=∑j=0B−1(1−p)junder independent identical attempts.P(\text{success by }B)=1-(1-p)^B,\qquad \mathbb E[N_B]=\sum_{j=0}^{B-1}(1-p)^j\quad\text{under independent identical attempts}.

The second expression follows by counting the probability of reaching each attempt. Real retries can repeat the same mistake, and correction prompts change the distribution. Do not use this formula as a guarantee for correlated model outputs. Log both success and attempts; retries consume latency and money even when final formatting succeeds.

Geng and colleagues compare efficiency on commonly covered schema instances to avoid giving an easy subset an unfair speed advantage. Their empirical coverage is based on finite runs; true coverage means exact agreement with schema semantics. Neither implies that a factually wrong invoice is correct. Constrained decoding, discussed in its own article, can restrict generation paths; post-generation validation still has a distinct job.

Find the layer that should reject it

  1. A quantity is written as 3.0, while another is written as true. What should this schema do?

Answer: Accept 3.0 as an integer-valued number, subject to the other checks, and reject true. JSON booleans and numbers are distinct, regardless of Python’s inheritance rules.

  1. Why does the notebook record with quantity 2, unit price 4 and total 8 fail?

Answer: It satisfies the field rules and arithmetic, but the source price is 3.50 USD. Internal consistency does not establish source support.

  1. Compute the final acceptance rate from the four layer counts 11,6,5,2 out of 14 candidates.

Answer: Multiply 11/14 by 6/11 by 5/6 by 2/5 to obtain 2/14, or 1/7. The conditional denominators refer to the surviving candidates at each stage; independence is not required.

  1. The third candidate is correct, but the first two failed and the retry limit is 2. Should this call return success?

Answer: No. It returns a bounded failure after two attempts. The caller can explicitly start another workflow, but silently spending an extra attempt would violate the declared budget.

A format guarantee has a scope

Use RFC 8259 for JSON syntax and interoperability, JSON Schema Validation for the field and format rules, and Core for applicator behavior. The selected 2020-12 specification text was published in June 2022; the dialect name is not its publication date. JSONSchemaBench, sections 4–5, provides the distinction between efficiency, observed coverage and full semantic coverage. This program’s fixture and hand-written validator reproduce none of the benchmark engines or its performance claims.

Make a prediction, then check

The unit price and total agree, but the product is absent from the source catalogue. Is the extraction verified?

Choose one answer

Learning objectives

  • Distinguish syntax, schema adherence, cross-field consistency and factual support.
  • Run the bounded original example and explain the failure cases.

Prerequisites & connections

Explore related knowledge →

References

  1. Generating Structured Outputs from Language Models: Benchmark and Studies — v1
    Saibo Geng; Hudson Cooper; Michał Moskal; Samuel Jenkins; Julian Berman; Nathan Ranchin; Robert West; Eric Horvitz; Harsha Nori · 2025
  2. RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format
    Tim Bray, editor; IETF · 2017
  3. JSON Schema Validation — Draft2020-12, June2022 specification
    Austin Wright; Henry Andrews; Ben Hutton · 2022
  4. JSON Schema Core — Draft2020-12, June2022 specification
    Austin Wright; Henry Andrews; Ben Hutton; Greg Dennis · 2022

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author. Read PDF3–6 text and viewed PDF7 section5:9558 schemas in Table1, efficiency on common covered instances, declared/empirical/true coverage, single greedy run and format-enabled validation. No benchmark replicated. New scoped reading: sections4–6 relevant HTML text, duplicate-name SHOULD and interoperability behavior, arrays and numeric grammar opening; existing Source object preserved. Read sections6.1.1/6.1.2,6.5.3,7.2.1/7.2.2: numeric integer semantics, enum, required and format vocabularies. HTML text only. Read section10.3.2.3: additionalProperties and its same-schema dependencies; no complete validator implementation claimed. 4 paired equations and four explained exercises. Four layer counts11/6/5/2, numeric integer versus boolean, exact long decimals, duplicate/nonfinite/huge exponent/depth/size rejection and bounded retries checked. One authored contract, not a general JSON Schema engine.

  • Four layer counts11/6/5/2, numeric integer versus boolean, exact long decimals, duplicate/nonfinite/huge exponent/depth/size rejection and bounded retries checked. One authored contract, not a general JSON Schema engine.
  • Four computed SVG variants per topic;9 numeric/geometry tests and24 responsive cases passed. Eight selected final captures directly viewed. Full article acceptance recorded separately.
  • Final page inspection found missing spaces at English prose number boundaries. Inserted only the explicitly recorded spaces; protected formulas, code, inline literals, links and frontmatter unchanged. Frozen originals retained; exact insertion regression and renewed page checks required.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.