content/cookbook/05-node/85-repair-json-with-jsonrepair.mdx
When generating structured outputs, language models sometimes produce malformed JSON output. This can happen due to:
With AI SDK v6, a practical pattern is to generate text, repair it, then parse and validate it. Combined with the jsonrepair library, you can automatically fix many common JSON issues.
First, install the jsonrepair library:
pnpm add jsonrepair
Here's how to use jsonrepair with generateText:
import { generateText, Output } from 'ai';
import { safeParseJSON } from '@ai-sdk/provider-utils';
__PROVIDER_IMPORT__;
import { jsonrepair } from 'jsonrepair';
import { z } from 'zod';
const recipeSchema = z.object({
recipe: z.object({
name: z.string(),
ingredients: z.array(
z.object({
name: z.string(),
amount: z.string(),
}),
),
steps: z.array(z.string()),
}),
});
const result = await generateText({
model: __MODEL__,
output: Output.text(),
prompt: 'Generate a lasagna recipe.',
});
const repairedText = jsonrepair(result.text);
const parseResult = safeParseJSON({ text: repairedText });
if (!parseResult.success) {
throw parseResult.error;
}
const output = recipeSchema.parse(parseResult.value);
console.log(output.recipe);
This flow has three steps:
Output.text()).jsonrepair.The jsonrepair library can automatically fix many common issues:
{"name": "test" -> {"name": "test"}{'name': 'test'} -> {"name": "test"}{name: "test"} -> {"name": "test"}{"items": [1, 2, 3,]} -> {"items": [1, 2, 3]}jsonrepair handles many cases, it cannot fix all malformed JSON (e.g., semantically incorrect data that happens to be valid JSON)maxOutputTokens or simplifying your schema