Skip to content

Validate AI-Generated JSON Before You Use It

AI output can look tidy and still break the next step in your workflow. A missing quote stops parsing, a wrong field type breaks an API, and a perfectly valid date can describe an impossible state. A short local validator gives you a clear boundary before data is stored or acted on.

This example uses Python’s standard json module and the open-source jsonschema package. It runs on your computer, needs no model call, and checks three separate questions: can the text be parsed, does the value match your contract, and does it make sense for your application?

Three layers of JSON validation

Syntax asks whether the text is JSON at all. Python’s json.loads() converts a string into Python values and raises JSONDecodeError, an error that reports where parsing stopped, when the document is malformed. The Python JSON documentation also documents the command-line check with python -m json.

Schema asks whether the parsed value has the expected shape. A JSON Schema can require fields, restrict values with an enum, check types, and validate formats. The jsonschema validation documentation shows Draft 2020-12 validators, iter_errors(), schema checking, and opt-in format checking.

Semantics asks whether the fields agree with one another. For example, a task marked done should have a completion timestamp. This last layer is application logic. A schema can describe a structure, but it cannot know every business rule you care about.

A small contract for task results

Suppose an AI assistant extracts a task from a conversation. The contract below requires a title, a status, two date fields, and a confidence number between zero and one. It permits completed_at to be null because a pending task has not finished yet.

{
  "title": "Renew domain",
  "status": "pending",
  "due_date": "2026-10-03",
  "completed_at": null,
  "confidence": 0.98
}

That sample is a useful AI input, but it is not automatically true. The validator can confirm that the value follows the contract. You still need to decide whether the task was extracted from the right conversation and whether the date is the one your calendar or source system actually contains.

Complete local validator in Python

Install the only third-party dependency once with python -m pip install "jsonschema[format]". Save the following as validate_ai_json.py and run it with your local Python interpreter. The code checks the schema itself before checking any AI output, then reports the first failure in each demonstration case.

import json
from jsonschema import Draft202012Validator, FormatChecker

SCHEMA = {
    "$schema": Draft202012Validator.META_SCHEMA["$id"],
    "type": "object",
    "additionalProperties": False,
    "required": ["title", "status", "due_date", "completed_at", "confidence"],
    "properties": {
        "title": {"type": "string", "minLength": 1},
        "status": {"type": "string", "enum": ["pending", "done"]},
        "due_date": {"type": "string", "format": "date"},
        "completed_at": {"type": ["string", "null"], "format": "date-time"},
        "confidence": {"type": "number", "minimum": 0, "maximum": 1},
    },
}

VALID = '''{
  "title": "Renew domain",
  "status": "pending",
  "due_date": "2026-10-03",
  "completed_at": null,
  "confidence": 0.98
}'''

SCHEMA_FAILURE = '''{
  "title": "Renew domain",
  "status": "maybe",
  "due_date": "2026-10-03",
  "completed_at": null,
  "confidence": 0.98
}'''

SEMANTIC_FAILURE = '''{
  "title": "Renew domain",
  "status": "done",
  "due_date": "2026-10-03",
  "completed_at": null,
  "confidence": 0.98
}'''

MALFORMED = '{"title": "Renew domain", "status": "pending"'


def semantic_errors(item):
    problems = []
    if item["status"] == "done" and not item["completed_at"]:
        problems.append("status=done requires completed_at")
    if item["status"] == "pending" and item["completed_at"]:
        problems.append("status=pending must not have completed_at")
    return problems


def reject_constant(value):
    raise ValueError(f"non-JSON numeric value: {value}")


def unique_object(pairs):
    item = {}
    for key, value in pairs:
        if key in item:
            raise ValueError(f"duplicate object key: {key}")
        item[key] = value
    return item


def check(label, raw):
    try:
        item = json.loads(raw, parse_constant=reject_constant, object_pairs_hook=unique_object)
    except json.JSONDecodeError as error:
        print(f"{label}: MALFORMED JSON at line {error.lineno}, column {error.colno}")
        return
    except ValueError as error:
        print(f"{label}: STRICT JSON FAIL: {error}")
        return

    errors = sorted(
        Draft202012Validator(SCHEMA, format_checker=FormatChecker()).iter_errors(item),
        key=lambda error: list(error.path),
    )
    if errors:
        print(f"{label}: SCHEMA FAIL: {errors[0].message}")
        return

    problems = semantic_errors(item)
    if problems:
        print(f"{label}: SEMANTIC FAIL: {problems[0]}")
        return
    print(f"{label}: PASS")


Draft202012Validator.check_schema(SCHEMA)
for label, raw in [
    ("valid", VALID),
    ("schema failure", SCHEMA_FAILURE),
    ("semantic failure", SEMANTIC_FAILURE),
    ("malformed", MALFORMED),
    ("nonfinite", VALID.replace("0.98", "NaN")),
    ("bad timestamp", VALID.replace('"pending"', '"done"').replace("null", '"not-a-timestamp"')),
    ("duplicate key", VALID.replace('"confidence": 0.98', '"confidence": 0.01, "confidence": 0.98')),
]:
    check(label, raw)

Install the format extra as shown above: some format checks, including date-time checking, depend on optional packages. FormatChecker() enables those checks. Without the required format dependency, an unavailable check can silently succeed.

The parser rejects NaN and infinity explicitly because Python accepts those values by default even though they are outside the JSON specification. Duplicate keys are rejected too, so a later value cannot silently overwrite an earlier one.

The schema check catches "maybe" before application logic runs. The semantic function then applies rules that belong to your workflow, where the meaning of done is known.

Expected output for each failure type

Running the file locally produces the following outcomes. The accepted case passes all three layers. The other cases show why a single “valid JSON” check is too weak for automation.

valid: PASS
schema failure: SCHEMA FAIL: 'maybe' is not one of ['pending', 'done']
semantic failure: SEMANTIC FAIL: status=done requires completed_at
malformed: MALFORMED JSON at line 1, column 46
nonfinite: STRICT JSON FAIL: non-JSON numeric value: NaN
bad timestamp: SCHEMA FAIL: 'not-a-timestamp' is not a 'date-time'
duplicate key: STRICT JSON FAIL: duplicate object key: confidence

The malformed example never reaches schema validation because there is no Python object to validate. The schema failure is parseable JSON with an invalid field value. The semantic failure has valid JSON and a valid schema, yet the two fields contradict each other.

Why valid JSON does not prove factual correctness

Imagine the same shape contains "due_date": "2026-10-03". JSON and the schema can confirm that the value has a valid date format. They cannot confirm that a renewal is really due that day, that the task belongs to the right person, or that the AI copied the date from the source correctly.

Factual checks need evidence from the system that owns the fact. Compare an extracted invoice number with the invoice file, look up a product identifier in your catalog, or require a human review for high-impact actions. Treat validation as a gate before use, not as a truth detector.

A repeatable local validation routine

  1. Keep the raw AI response and reject oversized or unexpected input before parsing.
  2. Parse with json.loads() and record the line and column for a syntax error.
  3. Check the schema, including required fields, types, allowed values, and formats.
  4. Run semantic rules for relationships that only your application understands.
  5. Verify important facts against an authoritative source before writing to a database or triggering an action.

Keep the raw response beside the validation result during development. That makes a rejected output explainable and lets you improve the prompt or schema from real failures. Once the boundary is stable, the same local function can sit between any model response and your existing application code.

Frequently asked questions

Q1) Do I need an AI API to run this validator?

No. The example receives a string and validates it locally. You can paste a saved response into the variable, read it from a file, or pass it from an existing application after the model call has already finished.

Q2) Can JSON Schema check every business rule?

No. It is well suited to structure, types, required fields, allowed values, and supported formats. Cross-field rules, database lookups, permissions, and factual checks usually belong in ordinary application code or a trusted source system.

Q3) Why use iter_errors() instead of stopping at one error?

iter_errors() yields every schema error it finds, so a user interface or log can show several fixes at once. The example prints only the first one to keep the demonstration compact; production code can format the full list with each error path.

Leave a comment