JSON Generation
Generate structured JSON content based on prompts, messages, or schemas. Useful for creating API responses, structured records, or documents.
Basic JSON Generation
When you need to generate structured data with specific fields, use schema-based generation. This ensures the output follows your required format with proper data types. Learn more about basic JSON generation.
const {
data: { payload }
} = await unbody.generate
.json("Provide user details:", {
schema: {
type: "object",
properties: {
name: { type: "string" },
age: { type: "number" },
address: { type: "string" }
}
}
});
Generation with Zod Schema
When you need type-safe JSON generation, use Zod schemas to define your output structure. This approach provides full TypeScript integration and runtime validation.
import { z } from "zod";
const {
data: { payload }
} = await unbody.generate
.json("Provide user details:", {
schema: z.object({
name: z.string(),
age: z.number()
})
});
Multi-Message Generation
When you need to generate structured data through conversation, use Message-Based Input with Schema. This helps when you need to provide context or specific instructions before generating the final structured output.
import { z } from "zod";
const {
data: { payload },
} = await unbody.generate
.json(
[
{
role: "user",
content: "What is the structure of a business entity?",
},
{
role: "system",
content: "Explain in detail with examples."
},
],
{
schema: z.object({
companyName: z.string(),
employees: z.number(),
headquarters: z.string(),
}),
}
);
Learn more about advanced JSON generation features in our JSON Generation API Guide.