Valid JSON Isn't Correct Data: Contracts for Amount and Unit

hands the invoice or quotation to the parser and obtains a valid JSON, which only indicates that it can be read by the program.1200 is the unit price or the tot

Invoices and quotations are easy to misread. A bare number like 1200 could be a unit price or a total, and 1.200,50 means different things in different regions. A parser can return perfectly valid JSON that still gets these details wrong. This guide shows how to set stricter rules for each extracted value, so that a value is only stored when its meaning, currency, source page, and location can be checked.

The example uses a synthetic quotation fragment that was typed by hand. No OCR or model evaluation was run on real documents, so the results show how the validation logic behaves and do not measure recognition accuracy. If you build an extraction pipeline, you can reuse the same contracts and acceptance rules.

The approach separates two jobs. The parser or model proposes candidate values, and a deterministic validator decides whether a candidate can be written to your database. Values that are missing or uncertain stay visible in the record instead of being silently replaced with zeros.

Can a valid JSON value be trusted? The short answer

No. Valid JSON only shows that a program can read the data, so each field also needs a contract that checks its format, currency, source page, quote, and coordinates before it is stored.

Your situationWhat to doWhy
A parser returns a number without a unit or currencyReject it or keep it as unverifiedSyntax alone cannot tell you whether 1200 is a unit price or a total
Amounts use European or regional separatorsAccept only the formats you have defined for that document type1.200,50 must be interpreted by region, not by a generic rule
A value comes with a page number and bounding boxCheck that the page exists and the box has finite coordinates inside the pageInvalid page numbers and coordinates can look like evidence
A required amount is missing or fails validationStore it with an explicit statusMissing, failed, and genuinely zero values are three different states
Your document is translatedKeep the amount, its unit, and its audit fields intactThe translated text must not break the link between amounts and units

Why does JSON syntax fall short for financial documents?

A JSON parser checks structure, not meaning. It cannot answer these questions:

  • Is 1200 the unit price or the total amount?
  • Where is the currency?
  • How should 1.200,50 be read according to regional conventions?
  • Do the returned page numbers actually exist?

Answering them requires a contract for each field, a clear rule for uncertain data, and a validator that runs on every candidate.

What does a field contract require?

Each field in the example must have more than a value. It needs its units, source page, original text, and coordinates.

Field constraints in the example

fieldconstraintWhy is it necessary
amountdecimal string, with the example constraint that it be non-negative and have two decimal placesavoids unintentionally introducing binary floating-point approximations
currencyThis scenario is limited to USDshould not secretly assume the Chinese yuan when no currency is specified
source.pageStarting from 1 and not exceeding the number of pagesallows users to return to the original text
source.quotemust be the in-page fragment provided by the calleris visible to the reviewer based on
source.bboxis a finite numerical value, located within the page rangeprevents empty frames and invalid coordinates from being masqueraded as evidence

Coordinate conventions

  • Coordinates use PDF points, with the origin at the upper-left corner of the currently defined page.
  • Upstream steps should first unify rotation, cropping, and the coordinate system.
  • Do not mix coordinates from different parsers directly.
  • This example only demonstrates the convention. It does not prove that the text actually sits inside the box.

How do you run the complete validation and rejection test?

The test uses only the Python standard library.

  1. Build each amount with Decimal from a string. Do not convert it to float first.
  2. Run the validator on each candidate and reject any candidate that breaks a contract.
  3. Keep the rejection reason with the record.

For precise decimal handling of amounts, see the Python decimal documentation.

from copy import deepcopy
from decimal import Decimal
import math
import re

pages = [{"width": 595, "height": 842,
          "text": "Total: USD 1,200.50\nDelivery within 10 days"}]

def validate(candidate, pages):
    if set(candidate) != {"amount", "currency", "source"}:
        raise ValueError("unexpected or missing field")
    raw = candidate["amount"]
    if not isinstance(raw, str) or not re.fullmatch(r"(?:0|[1-9][0-9]*)\.[0-9]{2}", raw):
        raise ValueError("amount must be a two-decimal string")
    if candidate["currency"] != "USD":
        raise ValueError("unsupported currency for this contract")
    src = candidate["source"]
    if not isinstance(src, dict) or set(src) != {"page", "quote", "bbox"}:
        raise ValueError("source contract mismatch")
    number = src["page"]
    if type(number) is not int or not 1 <= number <= len(pages):
        raise ValueError("page outside document")
    page = pages[number - 1]
    quote = src["quote"]
    if not isinstance(quote, str) or not quote or quote not in page["text"]:
        raise ValueError("source quote not found")
    match = re.fullmatch(r"Total: USD ([0-9]{1,3}(?:,[0-9]{3})*\.[0-9]{2})", quote)
    if not match or Decimal(match[1].replace(",", "")) != Decimal(raw):
        raise ValueError("amount does not agree with source")
    box = src["bbox"]
    if (not isinstance(box, list) or len(box) != 4
            or any(type(v) not in (int, float) or not math.isfinite(v) for v in box)):
        raise ValueError("invalid box values")
    x0, y0, x1, y1 = box
    if not (0 <= x0 < x1 <= page["width"] and 0 <= y0 < y1 <= page["height"]):
        raise ValueError("box outside page or empty")
    return {"amount": str(Decimal(raw)), "currency": "USD", "source": deepcopy(src)}

good = {"amount": "1200.50", "currency": "USD", "source": {
    "page": 1, "quote": "Total: USD 1,200.50", "bbox": [40, 70, 260, 90]}}
assert validate(good, pages)["amount"] == "1200.50"
print("PASS valid source-linked amount: USD 1200.50")
bad_cases = []
wrong = deepcopy(good); wrong["amount"] = "12000.50"; bad_cases.append(wrong)
wrong = deepcopy(good); wrong["source"]["page"] = 2; bad_cases.append(wrong)
wrong = deepcopy(good); wrong["source"]["bbox"][2] = float("nan"); bad_cases.append(wrong)
wrong = deepcopy(good); wrong["source"]["bbox"][0] = 300; bad_cases.append(wrong)
for index, wrong in enumerate(bad_cases, 1):
    try:
        validate(wrong, pages)
        raise AssertionError("bad candidate accepted")
    except ValueError as error:
        print(f"PASS rejection {index}: {error}")

Why is the amount pattern so strict?

The pattern accepts only the English money format shown in the example. It rejects:

  • European-style decimals
  • negative numbers
  • refund amounts in parentheses
  • other currencies
  • four-digit numbers without thousand separators

In a real system, choose the rules for each document type and region separately. Do not remove all commas, periods, and spaces from every input, because that can silently change the meaning of a value.

Before you widen the input scope, write positive and negative examples for each permitted format.

How should multi-currency invoices be handled?

  • Keep the original currency amount, the currency type, and the source of the exchange rate in separate fields.
  • If no exchange rate is available, do not convert the amount.

Does having a source mean the value is proven?

No. The validator checks that the quote appears in the text of the current page and that the amount matches the constrained format. It does not check that the bounding box encloses the original text, and it does not decide whether a line is the true final total in business terms.

Several issues can still slip through:

  • The text layer may come from an OCR process that made errors.
  • The same page may contain several totals.

So the field contract is only the starting point. You still need to:

  • check consistency across the document,
  • choose between candidates on the same page,
  • work out how subtotals, total tax, and the total relate,
  • spot-check results manually.

Until these steps pass, store critical business values with a "to be verified" status rather than "confirmed". Also keep three states apart: a missing amount, a validation failure, and a value that is genuinely zero.

How do you put this into a document workflow?

Keep the summary of the original document, assign a processing version to each extraction record, and save the reason for every rejection. A translation step should use the same audit fields. The main text can be translated into another language, but the link between significant amounts and their units must stay intact.

You can handle this kind of work with OmniDoc. The contract and code in this guide do not depend on the OmniDoc product API, and they do not assume any interface that has not been published.

The final output should let you trace any field back to its original page. JSON is the exchange format. The contracts, the evidence, and the acceptance criteria decide whether the data can actually be used.

🎯 Which approach fits you?

If you process multi-currency invoices

Store each original amount with its currency and the source of its exchange rate. Do not convert amounts without a rate.

If your documents use regional number formats

Define the accepted formats for each document type and region, and write positive and negative examples for each one.

If you translate documents for review

Keep the amount, its unit, and the audit fields together, so the translation does not break the link to the original figures.

❓ FAQ

1. Is valid JSON enough to trust extracted invoice data?

No. Valid JSON only shows that a program can read it. Each field also needs a contract that checks its format, currency, page, quote, and coordinates.

2. Why use a decimal string instead of a float for amounts?

Building the amount from a string avoids the binary floating-point approximations that a float conversion can introduce.

3. What should happen to a value when the source page does not exist?

It should be rejected. The page number must start at 1 and must not exceed the number of pages.

4. Does a bounding box prove that the text is in that location?

No. The validator checks that the coordinates are finite and inside the page range, but it does not check that the box encloses the original text.

📝 Summary

Valid JSON is only the starting point. Check every extracted value against a field contract, keep missing and uncertain data visible, and make sure every field can be traced back to its source page.

Try it now: upload a document and get it translated with the layout intact

Updated 2026-11-04