When supplier invoices arrive as PDFs or scans, teams extract fields with OCR or an LLM and send JSON to an ERP. Without a strict contract, drift breaks imports: missing POs become "" or guesses, floats round differently across services, or extra keys drop allowances.
A JSON Schema for invoice extraction fields guarantees shape, not accounting correctness. Unlike UBL XML—covered in Peppol invoice validation before ERP import—PDF extraction must constrain model output and hand clean values to deterministic code.
From three third-party sources (not Insonl clients)—Understanding JSON Schema, OpenAI Structured Outputs, and Peppol BIS Billing 3.0—this guide gives a worked contract for currency, line amounts, and missing fields, then splits schema checks from application code.
Why loose JSON schemas break ERP imports
One schema often serves both constrained LLM decoding and your integration validator. Three mismatches sit between them:
- Absent keys vs.
null. Standard JSON Schema objects allow omitted properties and extra keys by default, whilenullnever equals an absent key. OpenAI Structured Outputs (strict: true) requires every property inrequired,"additionalProperties": falseon every object, anobjectroot (notanyOf), andnullfor optionality. - JSON numbers vs. decimals. JSON Schema accepts
1and1.0alike asinteger, while default parsers map fractionalnumbervalues to binary floats (e.g., Pythonfloat, per Numeric types, unless configured with a decimal hook). Peppol BIS Billing 3.0 (§7.2) modelsAmount,Unit Price Amount,Quantity, andPercentageasDecimalvalues with separate currency and unit codes, showing two-decimal amounts (10000.25) and four-decimal prices/quantities (10000.1234) without capping price or quantity decimals. - Unanchored regexes and strict-mode limits. JSON Schema
patternuses unanchored ECMA-262 regexes ("p"matches"apple"), so patterns need^...$(String). OpenAI’s strict subset supportspattern, selectedformatvalues (date,date-time,email,uuid, etc.), numeric bounds,minItems/maxItems,$defs/$ref, andanyOf, while rejectingallOf,not,dependentRequired,dependentSchemas,if,then, andelse(fine-tuned models also droppattern,format,patternProperties, length, and numeric constraints). Caps:5,000properties,10nesting levels,1,000totalenumvalues (15,000chars max for any stringenumover250values), and120,000chars across property names, definition names,enum, andconststrings.
A worked JSON Schema contract for invoice extraction
(Illustrative schema—not from an Insonl client. Targets non-fine-tuned compatible models and standard validators; fine-tuned OpenAI models drop pattern, format, and minItems. Add "$schema": "https://json-schema.org/draft/2020-12/schema" at root for Draft 2020-12 validators per Dialect.)
{
"type": "object",
"additionalProperties": false,
"required": [
"invoice_number", "issue_date", "due_date", "purchase_order_number",
"document_currency_code", "tax_currency_code", "tax_total_in_accounting_currency",
"supplier", "lines", "tax_breakdown", "totals"
],
"properties": {
"invoice_number": {"type": "string", "description": "Supplier invoice ID as printed"},
"issue_date": {"type": "string", "format": "date", "description": "ISO 8601 YYYY-MM-DD"},
"due_date": {"anyOf": [{"type": "string", "format": "date"}, {"type": "null"}]},
"purchase_order_number": {"anyOf": [{"type": "string"}, {"type": "null"}]},
"document_currency_code": {"$ref": "#/$defs/currency_code"},
"tax_currency_code": {"anyOf": [{"$ref": "#/$defs/currency_code"}, {"type": "null"}]},
"tax_total_in_accounting_currency": {"anyOf": [{"$ref": "#/$defs/amount_2dp"}, {"type": "null"}]},
"supplier": {
"type": "object", "additionalProperties": false, "required": ["name", "tax_id"],
"properties": {"name": {"type": "string"}, "tax_id": {"anyOf": [{"type": "string"}, {"type": "null"}]}}
},
"lines": {"type": "array", "minItems": 1, "items": {"$ref": "#/$defs/invoice_line"}},
"tax_breakdown": {"type": "array", "items": {"$ref": "#/$defs/tax_subtotal"}},
"totals": {
"type": "object", "additionalProperties": false,
"required": [
"line_extension_total", "allowance_total", "charge_total", "tax_exclusive_total",
"tax_total", "tax_inclusive_total", "prepaid_amount", "payable_rounding_amount", "amount_due"
],
"properties": {
"line_extension_total": {"$ref": "#/$defs/amount_2dp"},
"allowance_total": {"anyOf": [{"$ref": "#/$defs/amount_2dp"}, {"type": "null"}]},
"charge_total": {"anyOf": [{"$ref": "#/$defs/amount_2dp"}, {"type": "null"}]},
"tax_exclusive_total": {"$ref": "#/$defs/amount_2dp"},
"tax_total": {"$ref": "#/$defs/amount_2dp"},
"tax_inclusive_total": {"$ref": "#/$defs/amount_2dp"},
"prepaid_amount": {"anyOf": [{"$ref": "#/$defs/amount_2dp"}, {"type": "null"}]},
"payable_rounding_amount": {"anyOf": [{"$ref": "#/$defs/amount_2dp"}, {"type": "null"}]},
"amount_due": {"$ref": "#/$defs/amount_2dp"}
}
}
},
"$defs": {
"currency_code": {"type": "string", "pattern": "^[A-Z]{3}$"},
"amount_2dp": {"type": "string", "pattern": "^-?[0-9]+(\\.[0-9]{1,2})?$"},
"decimal_4dp": {"type": "string", "pattern": "^-?[0-9]+(\\.[0-9]{1,4})?$"},
"tax_category_code": {"type": "string", "enum": ["AE", "B", "E", "G", "K", "L", "M", "O", "S", "Z"]},
"invoice_line": {
"type": "object", "additionalProperties": false,
"required": [
"line_number", "description", "seller_item_code", "quantity", "unit_code", "unit_price",
"base_quantity", "line_allowance", "line_charge", "line_net_amount", "tax_category", "tax_rate_percent"
],
"properties": {
"line_number": {"type": "string"},
"description": {"type": "string"},
"seller_item_code": {"anyOf": [{"type": "string"}, {"type": "null"}]},
"quantity": {"$ref": "#/$defs/decimal_4dp"},
"unit_code": {"anyOf": [{"type": "string"}, {"type": "null"}]},
"unit_price": {"$ref": "#/$defs/decimal_4dp"},
"base_quantity": {"anyOf": [{"$ref": "#/$defs/decimal_4dp"}, {"type": "null"}]},
"line_allowance": {"anyOf": [{"$ref": "#/$defs/amount_2dp"}, {"type": "null"}]},
"line_charge": {"anyOf": [{"$ref": "#/$defs/amount_2dp"}, {"type": "null"}]},
"line_net_amount": {"$ref": "#/$defs/amount_2dp"},
"tax_category": {"anyOf": [{"$ref": "#/$defs/tax_category_code"}, {"type": "null"}]},
"tax_rate_percent": {"anyOf": [{"$ref": "#/$defs/decimal_4dp"}, {"type": "null"}]}
}
},
"tax_subtotal": {
"type": "object", "additionalProperties": false,
"required": ["tax_category", "tax_rate_percent", "taxable_amount", "tax_amount"],
"properties": {
"tax_category": {"$ref": "#/$defs/tax_category_code"},
"tax_rate_percent": {"anyOf": [{"$ref": "#/$defs/decimal_4dp"}, {"type": "null"}]},
"taxable_amount": {"$ref": "#/$defs/amount_2dp"},
"tax_amount": {"$ref": "#/$defs/amount_2dp"}
}
}
}
}
Key design choices:
- Separate currency from amounts. Following Peppol’s ISO 4217 list and §11.6,
document_currency_codegoverns document and line amounts, while nullabletax_currency_codeandtax_total_in_accounting_currencyapply when the invoice currency differs from the national VAT currency.currency_codechecks three-letter code shape (anenumof active ERP currencies is tighter within OpenAI’s1,000-value cap), while amount patterns exclude currency symbols. - Encode money as ASCII decimal strings. Strings like
"1000.25"prevent binary float drift on default parsers and reject commas or symbols.[0-9](not\d) stays portable across JavaScript and Python; in Python validators, also enforce full-string matching without trailing\nin code.amount_2dpfollows Peppol’s two-decimal accounting cap (§9), whiledecimal_4dpsets an example four-decimal cap (Peppol leaves prices/quantities uncapped). For three-decimal currencies, widenamount_2dpto{1,3}and verify minor units in code. - Model missing fields as
null. Every object sets"additionalProperties": falseand lists all keys inrequired, usinganyOfwith{"type": "null"}for optional slots—includingtax_subtotal.tax_rate_percent, omitted in Peppol §8 for categoryO. Wrapping nullable enums (tax_category, matching Peppol’s UNCL5305 VAT subset) inanyOfalso satisfies standard JSON Schemaenumchecks onnull. Prompt the model to emitnullwhen optional fields are absent—and define a refusal or fallback path for non-invoice files, since required strings likeinvoice_numbercannot benulland OpenAI notes incompatible inputs can cause hallucinations.
Illustrative payload: what the schema catches vs. misses
(Illustrative example—not a real company, invoice, ERP instance, or Insonl client.)
{
"invoice_number": "DEMO-2026-109", "issue_date": "2026-11-19", "due_date": "2026-12-19",
"purchase_order_number": null, "document_currency_code": "EUR",
"tax_currency_code": "SEK", "tax_total_in_accounting_currency": "1375.50",
"supplier": {"name": "Demo Industrial Components AB", "tax_id": "SE556000000101"},
"lines": [{
"line_number": "1", "description": "Precision washer pack", "seller_item_code": "WSH-10",
"quantity": "120", "unit_code": "C62", "unit_price": "4.2500", "base_quantity": "1",
"line_allowance": "10.00", "line_charge": null, "line_net_amount": "500.00",
"tax_category": "S", "tax_rate_percent": "25"
}],
"tax_breakdown": [{"tax_category": "S", "tax_rate_percent": "25", "taxable_amount": "500.00", "tax_amount": "125.00"}],
"totals": {
"line_extension_total": "500.00", "allowance_total": null, "charge_total": null,
"tax_exclusive_total": "500.00", "tax_total": "125.00", "tax_inclusive_total": "625.00",
"prepaid_amount": null, "payable_rounding_amount": null, "amount_due": "625.00"
}
}
The schema blocks empty lines: [] (minItems: 1, as empty arrays otherwise pass JSON Schema arrays), formatted amounts like "€500.00" or "1,500.00", and extra keys like "notes". Strict OpenAI decoding on compatible models enforces format: "date" against "19/11/2026"; standard Draft 2020-12 validators disable format assertion by default unless enabled explicitly (a regex only checks YYYY-MM-DD shape, not calendar dates).
Three accounting defects still pass:
line_net_amountcould read"520.00"when(4.2500 / 1) * 120 - 10.00 = 500.00.tax_currency_codecould be"SEK"whiletax_total_in_accounting_currencyisnull.document_currency_codecould be"XXX"(ISO 4217 “no currency”), not an active ERP currency.
Which validation rules belong in application code
Split checks across three layers:
| Rule category | Best layer | Check and failure action |
|---|---|---|
Keys, types, null slots, regex, minItems |
Extraction strict schema | Enforced during decoding (strict: true); blocks bad shapes. |
| Refusals, truncation, content filter | Runtime code | Check Chat Completions refusal / finish_reason ("length", "content_filter") or Responses refusal items / status: "incomplete" (incomplete_details.reason: "max_output_tokens", "content_filter") (OpenAI). Route to review or retry. |
| Cross-field non-null coupling | Draft 2020-12 if/then or code |
Both keys stay present (null when empty), so dependentRequired passes "SEK" + null; use if/then (Conditionals) or code. |
| Decimal parsing, rounding, math | Deterministic app code | Parse to Decimal; verify formulas, VAT groups, minor-unit scale; hold mismatches. |
| Master data, FX, duplicates, PO match | ERP intake code | Verify active codes, treasury FX, duplicates, and three-way matching. |
Five code checks before staging an ERP draft:
- Line and document arithmetic. Recompute in exact decimals per Peppol BIS Billing 3.0 (§§8–10), treating null adjustments, prepayments, and rounding as
0:- Line net: round
(unit_price / (base_quantity ?? 1)) * quantityto two decimals (unit_priceis net price BT-146;base_quantity > 0), then add separately roundedline_chargeand subtract separately roundedline_allowance. - Tax-exclusive total:
sum(line_net_amount) - allowance_total + charge_total(nulls as0). - VAT breakdown: group lines and document adjustments by normalized
(tax_category, tax_rate_percent)(25=25.00; categoryOomits rate with0.00VAT), subtract allowances, add charges, applytax_rate_percent / 100to rated groups, round each category VAT to two decimals, and sum totax_total. Because this schema stores only aggregate totals, multi-rate invoices with document adjustments need an itemized array with category and rate; otherwise limit this check to invoices without document adjustments. - Tax-inclusive and payable totals:
tax_exclusive_total + tax_totalandtax_inclusive_total - prepaid_amount + payable_rounding_amount(nulls as0), without re-rounding sums of rounded amounts (§9).
- Line net: round
- Currency and FX checks. Match
document_currency_codeto active ERP ISO 4217 codes and minor-unit scale. Whentax_currency_codeis non-null, require non-nulltax_total_in_accounting_currencyand distinct currencies. Since Peppol §11.6 omits exchange rates, check FX plausibility against treasury rates in code. - Null-field routing. Route
nullonpurchase_order_numberorsupplier.tax_id: PO-backed vendors hold in staging; non-PO vendors go to G/L coding. - Stateful ERP controls. Run duplicate supplier invoice detection and three-way invoice matching before posting.
- Prevent schema-to-code drift. Per OpenAI, derive the schema from typed models (Pydantic or Zod helpers) or enforce parity in CI.
Where AI fits—and where deterministic code stays in charge
An LLM under strict JSON Schema maps PDF layouts into typed slots, backed by clear keys, description fields, and labeled evals (per OpenAI). Deterministic code owns accounting gates: decimal math, master-data lookups, duplicate checks, and ERP writes.
Audit your invoice extraction pipeline before scaling automation
Insonl is a Ho Chi Minh City engineering studio building ERP systems and operational AI. If your AP team fights rounding drift or missing fields on PDF invoices, start with our free AI workflow audit.
The audit is free; work after it is quoted separately.
Sources
- JSON Schema (third-party reference), Understanding JSON Schema: https://json-schema.org/understanding-json-schema/ (Dialect · Numeric · String · Object · Array · Null · Enum · Conditionals · Draft 2020-12 Validation)
- OpenAI (third-party docs), Structured model outputs: https://platform.openai.com/docs/guides/structured-outputs
- OpenPeppol (third-party spec, May 2026 Release), Peppol BIS Billing 3.0: https://docs.peppol.eu/poacc/billing/3.0/ (BIS · ISO 4217 · UNCL5305)
- Insonl: ERP Systems · Free AI workflow audit · Peppol Invoice Validation · Duplicate Supplier Invoice Detection · Three-Way Invoice Matching
