Validate AI-Generated JSON Before Using It in Your Web App

An editor asks for three article ideas. The model returns valid JSON, but one title is a number and another idea has a topic the CMS cannot file. Both survive JSON.parse(). Which suggestions should the preview show?

Here the contract is all or nothing. The application accepts one to three complete ideas or shows an error so the editor can try again. The same validator can check a pasted response in the browser and a provider response on the server.

Define the data contract before writing the prompt

Imagine a content management interface that asks an AI service to propose up to three article ideas. Each idea has a title, a summary and a topic selected from a fixed list.

A successful result should look like this:

{
  "ideas": [
    {
      "title": "Reduce image weight on mobile",
      "summary": "Compare responsive image candidates using DevTools.",
      "topic": "performance"
    }
  ]
}

Notice that the model is not being asked to publish anything, select an arbitrary URL or return executable HTML. The output is deliberately limited to suggestions that a human editor can review.

A prompt could specify:

Suggest one to three web development article ideas.
Return a JSON object with one key, "ideas", whose value is an array.
Each idea has title, summary and topic.
Use a title of 1 to 100 characters and a summary of 1 to 300.
Choose topic from accessibility, performance, security, or css.
Do not include Markdown fences or HTML.

If the provider supports constrained structured output, supply a matching schema using its documented API. That can reduce syntax and shape errors, but your application’s own validation remains necessary. Provider schema subsets, refusals, interrupted requests and output limits can affect the result.

Use the AI token counter to compare the prompt with longer versions containing example outputs. Its supported tokenizers provide useful estimates for compatible models, not exact usage figures for every provider. Our AI token budgeting guide covers how to leave space for the response itself.

Parse the response and validate its structure

JavaScript’s JSON.parse() verifies JSON syntax. It does not know that your application expects a title rather than a number, or that an array should contain no more than three items.

For this narrow example, a small explicit validator is sufficient. Larger contracts can use a maintained JSON Schema validator with a schema shared between the relevant application components.

Save the following as validate-ideas.mjs:

const topics = new Set([
  'accessibility', 'performance', 'security', 'css'
]);

function hasExactKeys(value, keys) {
  return value !== null && typeof value === 'object' &&
    !Array.isArray(value) &&
    Object.keys(value).length === keys.length &&
    keys.every(key => Object.hasOwn(value, key));
}

function boundedText(value, max, field) {
  if (typeof value !== 'string') {
    throw new Error(`${field} must be a string`);
  }
  const text = value.trim();
  const length = [...text].length;
  if (length < 1 || length > max) {
    throw new Error(`${field} has an invalid length`);
  }
  return text;
}

export function validateIdeas(raw) {
  if (typeof raw !== 'string') {
    throw new Error('Expected JSON text');
  }
  // A second line of defense; the HTTP reader must also bound input.
  if (new TextEncoder().encode(raw).byteLength > 16_384) {
    throw new Error('Response is too large');
  }

  let data;
  try {
    data = JSON.parse(raw);
  } catch {
    throw new Error('Invalid JSON syntax');
  }

  if (!hasExactKeys(data, ['ideas']) ||
      !Array.isArray(data.ideas) ||
      data.ideas.length < 1 || data.ideas.length > 3) {
    throw new Error('Expected one to three ideas');
  }

  return data.ideas.map((item, index) => {
    if (!hasExactKeys(item, ['title', 'summary', 'topic'])) {
      throw new Error(`Idea ${index + 1} has unexpected fields`);
    }
    if (!topics.has(item.topic)) {
      throw new Error(`Idea ${index + 1} has an unknown topic`);
    }
    return {
      title: boundedText(item.title, 100, 'Title'),
      summary: boundedText(item.summary, 300, 'Summary'),
      topic: item.topic
    };
  });
}

The validator checks the input type and size, requires the expected keys and constructs a fresh object containing only the accepted fields. It uses Unicode code points for text length, not user-perceived grapheme clusters. If you need exact visual character counts for complex emoji or combined characters, design that requirement separately.

One limitation of ordinary JSON.parse() is that duplicate object keys are resolved during parsing. If your protocol must reject duplicates, use a parser that detects them before values are overwritten.

Do not automatically extract JSON from arbitrary Markdown fences, or silently convert a numeric title into a string. Such recovery may conceal contract failures and make debugging harder. A controlled retry or a clear error is often preferable.

Render the result as text, not HTML

Validation does not make a string safe for every output context. A title that contains <img> may still satisfy the length and type rules. The browser must treat that title as text rather than markup.

Create a small browser demo next to the validator:

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Article idea preview</title>
<label for="response">AI response (JSON)</label><br>
<textarea id="response" rows="10" cols="50"></textarea><br>
<button id="preview" type="button">Validate and preview</button>
<p id="status" role="status"></p>
<ul id="ideas"></ul>
<script type="module">
  import { validateIdeas } from './validate-ideas.mjs';

  const input = document.querySelector('#response');
  const list = document.querySelector('#ideas');
  const status = document.querySelector('#status');
  input.value = JSON.stringify({ ideas: [{
    title: 'Build faster web pages',
    summary: 'Measure transfer sizes before optimizing.',
    topic: 'performance'
  }] }, null, 2);

  document.querySelector('#preview').addEventListener('click', () => {
    list.replaceChildren();
    try {
      const ideas = validateIdeas(input.value);
      for (const idea of ideas) {
        const li = document.createElement('li');
        const title = document.createElement('strong');
        const summary = document.createElement('p');
        title.textContent = idea.title;
        summary.textContent = `${idea.topic}: ${idea.summary}`;
        li.append(title, summary);
        list.append(li);
      }
      status.textContent = `${ideas.length} valid suggestion(s).`;
    } catch (error) {
      status.textContent = error.message;
    }
  });
</script>
</html>

Save it as index.html and serve both files locally, for example with python3 -m http.server 8000 --bind 127.0.0.1. Visit http://127.0.0.1:8000/ and try editing the JSON. JavaScript modules require a suitable HTTP origin rather than a direct file opening in many browsers.

The HTML escaping versus sanitizing guide explains why textContent is the right choice for this particular output. If your application genuinely needs rich markup, use a carefully configured sanitizer instead of assuming the model can produce trustworthy HTML.

Put the same checks on the server

The browser example is intentionally local. In a real application, keep your provider API key on the backend, call the provider there and validate the returned data before storing or forwarding it.

Use a bounded request and response reader, a timeout and provider output limits. Checking the length only after an unlimited response has been buffered does not protect the process from excessive memory consumption. Set separate byte limits for the HTTP response (which may include provider metadata) and the extracted JSON text passed to validateIdeas. For streaming providers, count bytes as chunks arrive, cancel on overflow and validate only the completed model output. Handle refusals and truncated results before handing text to the validator.

Your server should also distinguish provider failures, invalid output and application authorization failures. An unauthenticated browser must not be allowed to trigger an unlimited number of expensive generation requests. Apply rate limits, user quotas and spending controls.

The Mermaid live editor is useful for documenting the trust boundaries:

flowchart TD
    A[Browser request] --> B[Authenticate and limit usage]
    B --> C[Call AI provider]
    C --> D[Read bounded response]
    D --> E{Valid application data?}
    E -->|No| F[Return controlled error]
    E -->|Yes| G[Return normalized JSON]
    G --> H[Human review]

For a more detailed approach to error and authorization paths, see our API documentation with Mermaid tutorial.

Test the contract, not just the happy path

A small automated suite can catch accidental changes to the validator. Save this next to the module as validate-ideas.test.mjs:

import assert from 'node:assert/strict';
import { validateIdeas } from './validate-ideas.mjs';

const idea = { title: 'Test', summary: 'Example', topic: 'css' };
const encode = value => JSON.stringify({ ideas: value });
assert.deepEqual(validateIdeas(encode([idea])), [idea]);
assert.throws(() => validateIdeas('{'));
assert.throws(() => validateIdeas(encode([])));
assert.throws(() => validateIdeas(encode([idea, idea, idea, idea])));
assert.throws(() => validateIdeas(encode([{ ...idea, extra: true }])));
assert.throws(() => validateIdeas(encode([{ ...idea, title: 42 }])));
assert.throws(() => validateIdeas(encode([{ ...idea, topic: 'unknown' }])));
assert.throws(() => validateIdeas(encode([{ ...idea, summary: 'x'.repeat(301) }])));
assert.throws(() => validateIdeas(' '.repeat(16_385)));
assert.equal(validateIdeas(encode([{ ...idea, title: '<b>Test</b>' }]))[0].title,
  '<b>Test</b>');
console.log('All validation tests passed');

Run node validate-ideas.test.mjs using a modern Node.js release. The last assertion is intentional: HTML-like text is still text, and rendering it safely belongs to the output layer.

Once a real endpoint exists, use the cURL command line builder to test authenticated requests, malformed inputs and response status codes. Our guide to JSON, form data and multipart requests can help you choose the correct request content type.

Never confuse schema validation with permission

A validated object can still contain false statements, malicious suggestions or inappropriate content. If the AI reads untrusted webpages or documents, those inputs can try to influence its behavior. Schema validation limits the shape of the result, not its intent or truthfulness.

Keep privileged operations separate from generated suggestions. A model returning a valid action name must not bypass an authorization check, and a valid article title should not be published without the review required by your workflow. If you later add links, file paths or tool calls to the schema, give each field its own contextual validation and permission rules.

Monitor rejection rates and provider usage without logging confidential prompts or raw customer documents unnecessarily. Use a limited retry policy and a clear fallback when generation fails.

Premium is coming soon

An optional premium subscription to remove ads is planned. Subscriptions are not available yet.

You can keep using our free tools without an account.