Beyond Valid JSON: Checking AI-Generated Data Before Use

AI models can generate useful structured data, but an application should not assume that every response is ready to use. A response may contain missing fields, unexpected values, incorrect data types, or information that does not satisfy the application’s business rules.

These problems become especially important when generated JSON is passed directly into a database, an API request, or another automated process.

The solution is to treat model output as external input. Validate its structure, check its meaning, and handle incomplete or rejected responses before allowing them to affect the rest of the application.

Understand the Difference Between Valid JSON and Valid Data

JSON is a data format with a defined syntax. A response can be perfectly valid JSON and still be unsuitable for an application.

Consider this example:

{
  "name": "Example Product",
  "price": "unknown",
  "available": "yes"
}

The example is syntactically valid JSON. However, an application may expect price to be a number and available to be a Boolean value.

Another response might contain the correct data types but omit a required field.

This is why parsing JSON is only the first validation step. Developers also need to check the expected structure and the rules that apply to each field.

Define a Schema Before Requesting Model Output

A schema describes the structure that an application expects to receive.

For example, a simple product object might require:

  • name: A string.
  • price: A number.
  • available: A Boolean value.
  • category: A string selected from an approved list.

Defining these requirements before calling the model makes the interface between the AI component and the application easier to understand.

It also helps identify problems early. If a field is optional, make that explicit. If an empty value is not allowed, specify the requirement rather than leaving the model to guess.

For larger applications, the schema should be treated as part of the software interface and maintained alongside the code that consumes it.

Use Structured Output Features Where Available

Some AI APIs support structured output modes that constrain responses to a developer-provided JSON Schema.

OpenAI’s Structured Outputs feature is one example. It is designed to make completed, non-refusal model responses adhere to a supplied schema.

Documentation: OpenAI API: Structured Outputs.

This is more reliable than asking a model to “return JSON only” and hoping that the result follows the expected format.

However, schema-constrained output does not eliminate every application-level validation requirement. The API documentation also explains that developers still need to handle refusals, incomplete responses, API errors, and business rules that are not expressed in the schema.

Parse the Response and Handle Errors

After receiving a model response, the application should first check whether the request completed successfully and whether the output is complete.

Then parse the JSON using the programming language’s standard JSON parser or a suitable library.

A simplified JavaScript example looks like this:

function parseModelJson(rawText) {
  try {
    const data = JSON.parse(rawText);

    if (
      typeof data.name !== "string" ||
      typeof data.price !== "number" ||
      typeof data.available !== "boolean"
    ) {
      throw new Error("Unexpected data structure");
    }

    return data;
  } catch (error) {
    console.error("Invalid model response:", error);
    return null;
  }
}

This example checks basic field types. A production application should also verify that values fall within acceptable ranges and that required fields are present.

For example, a negative product price may be invalid even though it is a valid number. Similarly, an empty product name may satisfy a basic string check but still be unusable.

Validate Business Rules Separately

Schema validation checks the shape of the data. Business validation checks whether the data makes sense for the application.

Consider an appointment scheduling application. Its schema may require a date, a time, and a service name. Business rules may additionally require that the date is in the future, that the service is available, and that the selected time falls within permitted operating hours.

These rules should be checked by application code rather than relying entirely on the model.

A useful validation process includes:

  • Checking required fields.
  • Checking data types.
  • Checking allowed values and ranges.
  • Checking relationships between fields.
  • Checking whether the requested operation is permitted.

Keep the validation logic close to the part of the application that performs the operation. This makes it easier to test and maintain.

Handle Refusals and Incomplete Responses

A model response may not contain the expected JSON object. The model might refuse a request, the generation may stop before completion, or the API may return an error.

These situations should not be treated as ordinary parsing failures without further investigation.

Use separate handling paths for:

  • API request failures.
  • Incomplete model responses.
  • Explicit refusals.
  • JSON parsing errors.
  • Schema validation failures.
  • Business rule violations.

Different problems require different responses. A temporary network error may justify a retry, while an invalid value may require a new request or human review.

Avoid unlimited retry loops. Repeatedly asking a model to regenerate the same invalid response can increase costs without resolving the underlying issue.

Keep Untrusted Output Away from Sensitive Operations

Even when a response passes schema validation, its content should not automatically be trusted.

For example, an AI-generated JSON object should not be allowed to authorize a payment, change account permissions, or execute arbitrary code simply because it contains fields with the expected names.

Use normal application authorization, permission checks, and security controls before performing sensitive operations.

Also avoid inserting generated strings directly into SQL queries or executable code. Use parameterized database operations and appropriate output handling for the destination where the data will be used.

Test the Validation Process with Failure Cases

Testing only successful model responses creates a false sense of security.

Prepare test cases that include missing fields, incorrect types, empty strings, unexpected enum values, invalid dates, and incomplete JSON.

Also test responses that are structurally correct but violate business rules.

For each case, confirm that the application rejects or safely handles the response without performing unintended actions.

Keep useful error logs, but avoid recording API keys, personal information, or other sensitive data unnecessarily.

AI-generated JSON can make application workflows more flexible, but flexibility should not come at the expense of predictable behavior. A clear schema, independent validation, and deliberate error handling provide a much safer foundation for using model-generated data in real software.

← Back to Home