insonl
← journal

A JSON Schema for Invoice Fields Your ERP Can Validate

date
21 November 2026
by
Insonl
read
7 min read

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, while null never equals an absent key. OpenAI Structured Outputs (strict: true) requires every property in required, "additionalProperties": false on every object, an object root (not anyOf), and null for optionality.
  • JSON numbers vs. decimals. JSON Schema accepts 1 and 1.0 alike as integer, while default parsers map fractional number values to binary floats (e.g., Python float, per Numeric types, unless configured with a decimal hook). Peppol BIS Billing 3.0 (§7.2) models Amount, Unit Price Amount, Quantity, and Percentage as Decimal values 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 pattern uses unanchored ECMA-262 regexes ("p" matches "apple"), so patterns need ^...$ (String). OpenAI’s strict subset supports pattern, selected format values (date, date-time, email, uuid, etc.), numeric bounds, minItems/maxItems, $defs/$ref, and anyOf, while rejecting allOf, not, dependentRequired, dependentSchemas, if, then, and else (fine-tuned models also drop pattern, format, patternProperties, length, and numeric constraints). Caps: 5,000 properties, 10 nesting levels, 1,000 total enum values (15,000 chars max for any string enum over 250 values), and 120,000 chars across property names, definition names, enum, and const strings.

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:

  1. Separate currency from amounts. Following Peppol’s ISO 4217 list and §11.6, document_currency_code governs document and line amounts, while nullable tax_currency_code and tax_total_in_accounting_currency apply when the invoice currency differs from the national VAT currency. currency_code checks three-letter code shape (an enum of active ERP currencies is tighter within OpenAI’s 1,000-value cap), while amount patterns exclude currency symbols.
  2. 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 \n in code. amount_2dp follows Peppol’s two-decimal accounting cap (§9), while decimal_4dp sets an example four-decimal cap (Peppol leaves prices/quantities uncapped). For three-decimal currencies, widen amount_2dp to {1,3} and verify minor units in code.
  3. Model missing fields as null. Every object sets "additionalProperties": false and lists all keys in required, using anyOf with {"type": "null"} for optional slots—including tax_subtotal.tax_rate_percent, omitted in Peppol §8 for category O. Wrapping nullable enums (tax_category, matching Peppol’s UNCL5305 VAT subset) in anyOf also satisfies standard JSON Schema enum checks on null. Prompt the model to emit null when optional fields are absent—and define a refusal or fallback path for non-invoice files, since required strings like invoice_number cannot be null and 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_amount could read "520.00" when (4.2500 / 1) * 120 - 10.00 = 500.00.
  • tax_currency_code could be "SEK" while tax_total_in_accounting_currency is null.
  • document_currency_code could 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:

  1. 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)) * quantity to two decimals (unit_price is net price BT-146; base_quantity > 0), then add separately rounded line_charge and subtract separately rounded line_allowance.
    • Tax-exclusive total: sum(line_net_amount) - allowance_total + charge_total (nulls as 0).
    • VAT breakdown: group lines and document adjustments by normalized (tax_category, tax_rate_percent) (25 = 25.00; category O omits rate with 0.00 VAT), subtract allowances, add charges, apply tax_rate_percent / 100 to rated groups, round each category VAT to two decimals, and sum to tax_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_total and tax_inclusive_total - prepaid_amount + payable_rounding_amount (nulls as 0), without re-rounding sums of rounded amounts (§9).
  2. Currency and FX checks. Match document_currency_code to active ERP ISO 4217 codes and minor-unit scale. When tax_currency_code is non-null, require non-null tax_total_in_accounting_currency and distinct currencies. Since Peppol §11.6 omits exchange rates, check FX plausibility against treasury rates in code.
  3. Null-field routing. Route null on purchase_order_number or supplier.tax_id: PO-backed vendors hold in staging; non-PO vendors go to G/L coding.
  4. Stateful ERP controls. Run duplicate supplier invoice detection and three-way invoice matching before posting.
  5. 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