Output Parsers and Zod Validation
Even if you use Assistant Prefilling or Tool Forcing, the Anthropic API always returns a string.
If your application expects an array of objects to map over in React, calling JSON.parse(responseString) is dangerous. What if the string is slightly malformed? What if Claude returned { name: "Bob" } but your database requires { fullName: "Bob" }?
Your app will crash in production. To fix this, you need an Output Parser and a schema validator like Zod.
What is Zod?
Zod is a popular TypeScript/JavaScript library for schema declaration and validation. It allows you to strictly define exactly what a JSON object must look like, and it will throw a highly specific error if the data doesn't match.
Building a Bulletproof Parser
Let's build a pipeline that extracts users from a text and guarantees the output is perfectly formatted.
Step 1: Define the Zod Schema
const { z } = require('zod');
// Define exactly what the data must look like
const UserSchema = z.object({
fullName: z.string(),
age: z.number().int().positive(),
role: z.enum(["admin", "user"])
});
// We expect an array of these users
const ResponseSchema = z.array(UserSchema);
Step 2: Get the AI Output
// Assume Claude outputs this string:
const aiOutputString = '[{"fullName": "Bob", "age": 40, "role": "admin"}]';
Step 3: Parse and Validate
try {
// First, parse the string into raw JavaScript objects
const rawJson = JSON.parse(aiOutputString);
// Second, force the raw JSON through the Zod schema validator
const validatedData = ResponseSchema.parse(rawJson);
// If we reach this line, the data is 100% guaranteed to be perfect!
console.log(validatedData[0].fullName);
} catch (error) {
// Zod will throw an error if the schema doesn't match
console.error("Validation Failed:", error.errors);
// Optional: Send the error back to Claude so it can fix its own mistake!
}
Self-Correcting Agents
The real power of combining LLMs with Zod is self-correction.
If Zod throws an error (e.g., Expected number, received string for 'age'), you can catch that exact error message, append it to the chatHistory, and automatically prompt Claude again:
"Your previous output failed validation with this error: [Zod Error]. Please rewrite the JSON to fix it."
This creates an incredibly resilient backend. The AI generates data, Zod strictly validates it, and if it fails, the AI autonomously fixes its own formatting errors before the frontend ever sees the data.