Back to Blog
Guides

How to Convert Contracts and Invoices Into JSON With Claude or ChatGPT

Anupama Nair, Growth Marketing Manager, Blackbee AI10 min read

Turn contract and invoice PDFs into structured JSON with Claude or ChatGPT. Copy-ready schemas, a no-code prompt, Python API code and validation checks.

Your contracts and invoices are full of useful data. Prices, payment terms, renewal dates, PO numbers, line items. The problem is that almost all of it is locked inside PDFs.

And a PDF is great for reading but terrible for working with. You can't sort it or compare it against anything, and you definitely can't feed it into your ERP without someone retyping it.

JSON fixes that. Put simply, once an invoice or contract is in JSON, it's structured data. You can check it, compare it, load it into a spreadsheet or pass it to another system. And the good news is that both Claude and ChatGPT are now very good at doing the conversion for you.

This guide walks through two ways to do it. The first needs nothing more than a chat window. The second uses the API and a few lines of Python, for when you want to process more than a handful of documents. Both use the same schemas, which you can copy straight from this post.

Why convert contracts and invoices to JSON?

JSON (JavaScript Object Notation) is a simple text format that stores data as labelled fields, so every value has a name like invoice_number or notice_period_days. That makes it easy for both people and software to read.

Here's what that unlocks for a finance team:

  • Invoices: you can check that totals add up and compare prices against your contracts before anything gets paid.
  • Contracts: you can track every renewal date and notice period in one place, and spot price-increase caps and payment terms without opening a single PDF.

Why does that matter so much? Because right now, most of that data is scattered and hard to read. Research from World Commerce & Contracting found that contract data can be spread across as many as 24 different systems in some organisations, and that almost 90% of business users find contracts difficult or impossible to understand. Getting the key terms into a structured format is the first step to actually using them.

Finance teams are moving fast on this. The Hackett Group's 2026 Finance Key Issues Study found that 33% of organisations are already scaling AI in accounts payable. That makes AP the most mature finance process for AI adoption.

Step 1: Decide what you want out of each document

Before you touch Claude or ChatGPT, decide exactly which fields you need. This is the step most people skip, and it's the one that makes the biggest difference to the quality of what comes back.

The list of fields, with their names and types, is called a schema. Here are two you can use as a starting point.

Invoice schema

json
{
  "type": "object",
  "properties": {
    "vendor_name": { "type": "string" },
    "vendor_tax_id": { "type": ["string", "null"] },
    "invoice_number": { "type": "string" },
    "invoice_date": { "type": "string", "description": "YYYY-MM-DD" },
    "due_date": { "type": ["string", "null"], "description": "YYYY-MM-DD" },
    "po_number": { "type": ["string", "null"] },
    "currency": { "type": "string", "description": "3-letter ISO code, e.g. USD" },
    "line_items": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "description": { "type": "string" },
          "quantity": { "type": "number" },
          "unit_price": { "type": "number" },
          "line_total": { "type": "number" }
        },
        "required": ["description", "quantity", "unit_price", "line_total"],
        "additionalProperties": false
      }
    },
    "subtotal": { "type": "number" },
    "tax_total": { "type": ["number", "null"] },
    "total": { "type": "number" },
    "payment_terms": { "type": ["string", "null"] }
  },
  "required": [
    "vendor_name", "vendor_tax_id", "invoice_number", "invoice_date",
    "due_date", "po_number", "currency", "line_items", "subtotal",
    "tax_total", "total", "payment_terms"
  ],
  "additionalProperties": false
}

Contract schema

json
{
  "type": "object",
  "properties": {
    "supplier_name": { "type": "string" },
    "contract_title": { "type": "string" },
    "effective_date": { "type": "string", "description": "YYYY-MM-DD" },
    "end_date": { "type": ["string", "null"], "description": "YYYY-MM-DD" },
    "auto_renews": { "type": "boolean" },
    "renewal_term_months": { "type": ["integer", "null"] },
    "notice_period_days": { "type": ["integer", "null"] },
    "payment_terms": { "type": ["string", "null"] },
    "price_increase_cap_percent": { "type": ["number", "null"] },
    "pricing": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "item": { "type": "string" },
          "unit_price": { "type": "number" },
          "unit": { "type": "string" },
          "currency": { "type": "string" }
        },
        "required": ["item", "unit_price", "unit", "currency"],
        "additionalProperties": false
      }
    },
    "termination_for_convenience": { "type": "boolean" },
    "governing_law": { "type": ["string", "null"] }
  },
  "required": [
    "supplier_name", "contract_title", "effective_date", "end_date",
    "auto_renews", "renewal_term_months", "notice_period_days",
    "payment_terms", "price_increase_cap_percent", "pricing",
    "termination_for_convenience", "governing_law"
  ],
  "additionalProperties": false
}

A few things about how these are written, because they're deliberate:

  • Every field is listed as required. Fields that might be missing from a document use ["string", "null"], so the model returns null instead of guessing. OpenAI's strict mode expects every property to be required, with nullable fields written as a type array, so this format works on both platforms.
  • additionalProperties is set to false on every object. Both Claude and OpenAI need this for strict schemas. It stops the model inventing extra fields.
  • Dates are strings with a format in the description. Asking for YYYY-MM-DD every time saves you a lot of clean-up later.
  • Numbers are numbers. Prices and totals use number so you can do maths on them straight away, without stripping out currency symbols first.

Add or remove fields to suit your business. If you've never written a schema before, json-schema.org has a friendly getting-started guide.

Step 2: Run the conversion

You've got two options here. Which one suits you comes down to how many documents you're dealing with.

Option A: Use the Claude or ChatGPT app (no code)

If you've got a few documents to convert, the chat apps are the quickest route.

  1. 1.Open Claude or ChatGPT and upload the invoice or contract PDF.
  2. 2.Paste in the prompt below, with the right schema underneath it.
  3. 3.Check the totals and dates against the original document.
  4. 4.Copy the JSON that comes back and save it as a .json file, or paste it into the next tool.

Here's the prompt:

prompt
Extract the data from the attached document and return it as JSON that
matches the schema below exactly.

Rules:
- Return only the JSON, with no explanation or markdown around it.
- Use null for any field that isn't in the document. Do not guess.
- Dates must be YYYY-MM-DD.
- Numbers must be plain numbers with no currency symbols or commas.
- For line items or pricing, include every row in the document.

Schema:
[paste the invoice or contract schema here]

This works well, and it's a great way to test your schema before you build anything bigger. But there's one thing to know. In the chat apps, the schema is guidance, so the model will usually follow it, but nothing forces it to. Always give the output a quick check, especially totals and dates.

A quick word on privacy. Contracts and invoices often contain sensitive commercial data and bank details. Check your company's AI policy before uploading them to any chat app, and use a business or enterprise account if your company provides one.

Option B: Use the API for guaranteed JSON

When you're ready to process documents in bulk, the API is the better route. Both Claude and OpenAI now offer structured outputs, which constrain the model's response to your schema so the JSON always matches it.

With Claude

Claude accepts PDFs directly as a document content block. You can send the file as base64 data or point Claude to a URL. According to Anthropic's PDF support docs, a single request can include up to 600 pages (100 if the model's context window is under 1M tokens), and Claude reads both the text and the page images, which helps with scanned documents and tables.

For structured outputs, you pass your schema in output_config.format. Anthropic's structured outputs docs confirm that no beta header is needed for this, and that it works across all current models.

python
import base64
import json
import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from your environment

with open("invoice_schema.json") as f:
    schema = json.load(f)

with open("invoice.pdf", "rb") as f:
    pdf_data = base64.standard_b64encode(f.read()).decode("utf-8")

message = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=4096,
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "document",
                "source": {"type": "base64", "media_type": "application/pdf", "data": pdf_data},
            },
            {
                "type": "text",
                "text": "Extract the invoice data. Use null for anything not in the document.",
            },
        ],
    }],
    output_config={"format": {"type": "json_schema", "schema": schema}},
)

invoice = json.loads(message.content[0].text)
print(invoice["invoice_number"], invoice["total"])

Swap invoice_schema.json for contract_schema.json and change the instruction text to convert contracts instead.

With ChatGPT (OpenAI API)

OpenAI's API also accepts PDFs, either uploaded as a file or sent as base64 data. Per OpenAI's file inputs guide, files need to be under 50 MB, and the API extracts both text and page images.

For structured outputs, set text.format to a JSON schema with strict: true in the Responses API.

python
import json
from openai import OpenAI

client = OpenAI()  # reads OPENAI_API_KEY from your environment

with open("invoice_schema.json") as f:
    schema = json.load(f)

uploaded = client.files.create(file=open("invoice.pdf", "rb"), purpose="user_data")

response = client.responses.create(
    model="gpt-6.2-astra",
    input=[{
        "role": "user",
        "content": [
            {"type": "input_file", "file_id": uploaded.id},
            {"type": "input_text", "text": "Extract the invoice data. Use null for anything not in the document."},
        ],
    }],
    text={
        "format": {
            "type": "json_schema",
            "name": "invoice",
            "schema": schema,
            "strict": True,
        }
    },
)

invoice = json.loads(response.output_text)
print(invoice["invoice_number"], invoice["total"])

Model names change often, so check each provider's docs for the latest model before you run this.

Things to watch for with the API

  • Check why the response stopped. With Claude, look at stop_reason. A value of max_tokens means the JSON may be cut off, so retry with a higher limit. A long contract with many pricing rows can need more tokens than you'd expect.
  • Keep schemas reasonably simple. Claude's docs list complexity limits, including a cap of 16 fields that use type arrays like ["string", "null"]. The two schemas above stay well inside it.
  • Expect a slower first request. The first time you use a new schema, Claude compiles it, which takes a moment. After that it's cached for 24 hours.
  • Control costs. A PDF page typically uses 1,500 to 3,000 tokens of text on Claude. If you're processing hundreds of documents, the Message Batches API is the cheaper option.

Step 3: Check the JSON before you trust it

Structured outputs guarantee the shape of the JSON, and that's all. A model can still misread a blurry number or pick up the wrong date. OpenAI's docs say this directly: validate any business rules the schema can't express.

So add a few simple checks after every extraction:

python
def check_invoice(inv):
    problems = []
    line_sum = round(sum(li["line_total"] for li in inv["line_items"]), 2)
    if abs(line_sum - inv["subtotal"]) > 0.01:
        problems.append(f"Line items add up to {line_sum}, subtotal says {inv['subtotal']}")
    expected_total = inv["subtotal"] + (inv["tax_total"] or 0)
    if abs(expected_total - inv["total"]) > 0.01:
        problems.append(f"Subtotal plus tax is {expected_total}, total says {inv['total']}")
    for li in inv["line_items"]:
        if abs(li["quantity"] * li["unit_price"] - li["line_total"]) > 0.01:
            problems.append(f"Line '{li['description']}' doesn't multiply out")
    return problems

For contracts, the checks are different. Make sure the end date comes after the effective date, and flag any contract where auto_renews is true but notice_period_days is null. That combination usually means the model missed the notice clause, and it's exactly the kind of gap that leads to renewals nobody approved.

Anything that fails a check goes to a person. Everything else can move on.

What you can do once your data is in JSON

This is where it gets useful. Once your invoices and contracts are both in JSON, you can start comparing them.

  • Check invoice prices against contract prices. Match invoice line items to the contract's pricing table and flag anything billed above the agreed rate. That's the heart of contract leakage.
  • Catch duplicates. Compare new invoices against ones you've already processed by vendor and amount, and by date. Our guide to duplicate payments explains which matches to look for.
  • Build a renewals calendar. Sort contracts by end date minus notice period, so you know every deadline before it passes.
  • Analyse spend. Load a few months of invoice JSON into a spreadsheet or ChatGPT's data analysis tool. Our post on using ChatGPT to analyse AP spend data has six ready-made prompts.

If you want to go further with invoices specifically, our earlier guide on ChatGPT invoice data extraction covers validation and exception routing in more depth.

Where the DIY approach runs out

This approach is genuinely useful, and for a few dozen documents a month it may be all you need. But as volumes grow, a few limits start to show.

Each extraction is a one-off. The model doesn't remember last month's invoices, so duplicate checks and contract comparisons are only as good as the code you write around it. Someone has to maintain that code and handle the exceptions, then get the results into your ERP. And none of it helps with the spend that never produces an invoice in the first place.

So what happens when you outgrow it? That's the gap Blackbee AI is built for. It's an agentic Intake-to-Pay platform that sits above your ERP as the financial decision and control layer.

Parse Agent pulls every field out of each invoice and gives it a confidence score, then checks it against what's already been received and paid. Clause Agent reads your contracts and turns the terms into active financial guardrails, so every invoice price gets checked against what you agreed. Once a decision is validated, Sync Agent posts it to your ERP, whether that's NetSuite, Sage Intacct, Dynamics 365, Workday or SAP.

Of course, every step in between stays within your explicit control. You choose what Blackbee AI handles, and it does only that, and does it well, with every decision showing its reasoning.

Want contracts and invoices checked against each other automatically? Book a demo and we'll show you how Blackbee AI's Parse Agent and Clause Agent work above your ERP.

Frequently Asked Questions

Buyer Questions