Use generateObject to get structured data from an LLM with the AI SDK
9/2/2025
LLMs often return free-form text, which can be hard to parse.
With the AI SDK, you can use generateObject
to directly enforce a typed JSON schema — no more brittle regex or string parsing.
import { openai } from '@ai-sdk/openai';
import { generateObject } from 'ai';
import { z } from 'zod';
const result = await generateObject({
model: openai('gpt-4.1'),
schema: z.object({
name: z.string(),
age: z.number(),
}),
prompt: "Extract the person's name and age: John is 42 years old.",
});
console.log(result.object);
// → { name: "John", age: 42 }
Why it’s great:
- Enforces strict structure with Zod
- No messy post-processing
- Safer integration with TypeScript
Use generateObject whenever you want predictable, typed data from an LLM.
Learn more about generateObject in the AI SDK documentation.
More Dev Tips
Discover more tips and tricks to level up your development skills
New: Your Idea. Our Experts. We'll Build Your SaaS For You.
Our 'Done For You' service simplifies the process, taking your concept and delivering a production-ready MVP or complete SaaS solution.
Start your scalable and production-ready SaaS today
Save endless hours of development time and focus on what's important for your customers with our SaaS starter kits for Next.js, Nuxt 3 and SvelteKit
Get startedStay up to date
Sign up for our newsletter and we will keep you updated on everything going on with supastarter.