content/docs/07-reference/01-ai-sdk-core/70-extract-json-middleware.mdx
extractJsonMiddleware()extractJsonMiddleware is a middleware function that extracts JSON from text content by stripping markdown code fences and other formatting. This is useful when using Output.object() with models that wrap JSON responses in markdown code blocks (e.g., ```json ... ```).
import { extractJsonMiddleware } from 'ai';
const middleware = extractJsonMiddleware();
<Snippet text={import { extractJsonMiddleware } from "ai"} prompt={false} />
<PropertiesTable content={[ { name: 'transform', type: '(text: string) => string', isOptional: true, description: 'Custom transform function to apply to text content. Receives the raw text and should return the transformed text. If not provided, the default transform strips markdown code fences.', }, ]} />
Returns a middleware object that:
```json and ```) from text contenttransform function is providedStrip markdown code fences from model responses when using structured output:
import {
generateText,
wrapLanguageModel,
extractJsonMiddleware,
Output,
} from 'ai';
import { z } from 'zod';
const result = await generateText({
model: wrapLanguageModel({
model: yourModel,
middleware: extractJsonMiddleware(),
}),
output: Output.object({
schema: z.object({
recipe: z.object({
name: z.string(),
steps: z.array(z.string()),
}),
}),
}),
prompt: 'Generate a lasagna recipe.',
});
console.log(result.output);
The middleware also works with streaming responses:
import {
streamText,
wrapLanguageModel,
extractJsonMiddleware,
Output,
} from 'ai';
import { z } from 'zod';
const { partialOutputStream } = streamText({
model: wrapLanguageModel({
model: yourModel,
middleware: extractJsonMiddleware(),
}),
output: Output.object({
schema: z.object({
recipe: z.object({
ingredients: z.array(z.string()),
steps: z.array(z.string()),
}),
}),
}),
prompt: 'Generate a detailed recipe.',
});
for await (const partialObject of partialOutputStream) {
console.log(partialObject);
}
For models that use different formatting, you can provide a custom transform:
import { extractJsonMiddleware } from 'ai';
const middleware = extractJsonMiddleware({
transform: text =>
text
.replace(/^PREFIX/, '')
.replace(/SUFFIX$/, '')
.trim(),
});
The middleware handles text content in two ways:
```json\n)\n```)This approach ensures efficient streaming while correctly handling code fences that may be split across multiple chunks.