Skip to content

JSON Is a Shape, Not a Guarantee

By Maksym Kuzmitskyi
6 min read
JSON Is a Shape, Not a Guarantee

JSON Is a Shape, Not a Guarantee

The assistant returns a string where the application expects an array. A retry fixes the brackets. The answer inside the brackets still contradicts the policy.

Those are two failures. I don't want one green parsing check to make them look like one solved problem.

For our fictional documentation assistant, a useful result must be readable by the application before we can examine whether it answers the question. Structured output helps with that first boundary. It does not make the second boundary disappear.

Syntax, structure and meaning

JSON, JavaScript Object Notation, is a text format for values such as objects, arrays, strings and numbers. Parsing checks whether a string follows that format and turns it into runtime values.

A schema describes the expected structure: which fields exist, their types and the alternatives allowed. A TypeScript type describes expectations during compilation. It does not validate JSON received at runtime merely because we assign the parsed value a type.

Semantic validation asks a different question: does the content mean something acceptable for this task? A source identifier can be a valid string and refer to no supplied document. A sentence can cite a real policy while misstating what it says.

I prefer to name each result after the check it passed. Parsed, structurally valid and supported by evidence are not interchangeable statuses.

Give missing information a real representation

Suppose the assistant must always return an answer string. What should it put there when no policy was supplied?

An empty string is ambiguous. A sentence explaining the missing document might accidentally enter a UI path that labels everything in that field as an answer. A forced source array can encourage invented references.

Instead, use two explicit alternatives: an answer with references, or a request for information. A discriminated union is a TypeScript union whose members have a distinguishing field, here called kind.

The following complete parser accepts JSON text and returns a validated application value or undefined. It intentionally supports only our tiny contract; a larger schema is a good reason to reuse an established validation library rather than keep expanding it.

type Answer = | { kind: 'answer'; text: string; sourceIds: string[] } | { kind: 'needs-information'; question: string }; function parseAnswer(payload: string): Answer | undefined { if (new TextEncoder().encode(payload).byteLength > 10_000) return undefined; let value: unknown; try { value = JSON.parse(payload); } catch { return undefined; } if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined; if (!('kind' in value)) return undefined; if (value.kind === 'needs-information') { if (Object.keys(value).some((key) => !['kind', 'question'].includes(key))) return undefined; if (!('question' in value) || typeof value.question !== 'string' || !value.question.trim()) { return undefined; } return { kind: 'needs-information', question: value.question.trim() }; } if (value.kind !== 'answer') return undefined; if (Object.keys(value).some((key) => !['kind', 'text', 'sourceIds'].includes(key))) return undefined; if (!('text' in value) || typeof value.text !== 'string' || !value.text.trim()) return undefined; if (!('sourceIds' in value) || !Array.isArray(value.sourceIds) || value.sourceIds.length === 0) { return undefined; } if (!value.sourceIds.every((id): id is string => typeof id === 'string' && id.trim().length > 0)) { return undefined; } return { kind: 'answer', text: value.text.trim(), sourceIds: value.sourceIds.map((id) => id.trim()) }; }

The size limit is a small example policy, not a universal safe payload size. It also measures the string after our application has received it. A production HTTP client needs its own response-size and timeout limits before buffering an arbitrarily large body.

Unexpected fields are rejected so a new model-produced field cannot silently acquire meaning in a later part of the application. None of these branches sends a request or writes a document.

Check what the parser really promises

These two payloads both parse as JSON. Only the second fits the answer structure:

const invalidShape = parseAnswer( '{"kind":"answer","text":"Approval is optional.","sourceIds":"release-policy-v3"}', ); const validShape = parseAnswer( '{"kind":"answer","text":"Approval is optional.","sourceIds":["release-policy-v3"]}', );

The first returns undefined because sourceIds is a string. The second returns an Answer. It is still an unsupported claim against our example policy, which requires approval.

The parser never received the policy. There is no plausible way for it to have checked that relationship. Adding a confidence number would not change the situation; a model-reported confidence is another generated value, not independent evidence.

After structural validation, ordinary code can check whether references belong to the supplied source set. Evaluations and review can then examine whether the answer is actually supported. Each stage has a smaller, clearer job.

Provider guarantees have a scope

Some providers constrain generation to a supported JSON schema. Constrained decoding means the generation process restricts possible outputs according to a format, rather than relying only on a sentence asking for JSON.

That is useful. I would use supported structured-output features where appropriate, then still inspect the response envelope and validate at my boundary.

Anthropic's structured-output guide, checked November 26, describes supported schema features and exceptions including refusals and generation limits. It also distinguishes constraints enforced by the API from checks performed by SDK helpers.

That means a familiar schema written in a library can be transformed before it reaches the provider. I would check the selected SDK's behavior rather than assume every local constraint became a generation constraint.

Our parser is not an implementation of constrained decoding. It runs after a string arrives. The examples establish its acceptance behavior offline, not a provider's reliability or compatibility with an arbitrary schema.

Invalid output is not always an invitation to retry

A retry may be appropriate for a transient failure or a correctable formatting issue. It can also repeat the same unsupported answer while adding cost.

A refusal, incomplete generation, missing source and invalid shape deserve distinct application outcomes. I would put limits on retries and preserve enough sanitized diagnostic information to identify which boundary failed.

In particular, I would not automatically increase output allowances until something parses. The task still has an approved cost and an unresolved reason for the earlier failure.

A narrow type is a useful beginning

What I like about this boundary is how ordinary it is. External data arrives. The application rejects values it cannot interpret. A validated value proceeds to more specific checks.

The model has not removed that familiar engineering responsibility. It has made the distinction between structural plausibility and correct content easier to overlook.

Our assistant can now return an explicit request for information instead of disguising uncertainty as an answer. To hold a useful conversation after that request, the next call needs to include what happened before. That history is another application decision, not an automatic property of an assistant-shaped interface.

Which failure does your code currently group under invalid response: malformed JSON, the wrong structure, or a valid object containing the wrong conclusion? I'd start by separating them.

A note from the author

I’m Maksym Kuzmitskyi, a senior software developer working mainly with React and TypeScript. I build frontend applications and design workflows for working with AI in software delivery. If this article connects with something you’re working on, I’d love to hear from you.

Telegram

More than a blog post

I share frontend news and the reasoning behind it throughout the day. Pick the language that feels natural to you.

Need to discuss your project? Get in touch.