typescriptintermediate
LLM JSON Output Parser
Parse and validate JSON responses from LLMs with retry logic and schema enforcement using Zod.
typescriptPress ⌘/Ctrl + Shift + C to copy
import { z } from 'zod';
function extractJSON(text: string): string | null {
const match = text.match(/```(?:json)?\s*([\s\S]*?)```/) ?? text.match(/\{[\s\S]*\}/);
return match ? (match[1] ?? match[0]).trim() : null;
}
export function parseLLMResponse<T>(rawText: string, schema: z.ZodType<T>): T {
const jsonStr = extractJSON(rawText);
if (!jsonStr) throw new Error('No JSON found in LLM response');
const parsed = JSON.parse(jsonStr);
return schema.parse(parsed);
}
// Usage
const ProductSchema = z.object({
name: z.string(),
price: z.number().positive(),
tags: z.array(z.string()),
});
const llmOutput = `Here is the product:\n\`\`\`json\n{"name": "Widget", "price": 29.99, "tags": ["tool", "hardware"]}\n\`\`\``;
const product = parseLLMResponse(llmOutput, ProductSchema);
console.log(product.name, product.price);Use Cases
- Extracting structured data from LLM responses
- Building type-safe AI data pipelines
- Validating AI-generated content schemas
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptbeginner
Express Zod Request Validation
Validate Express request body, params, and query with Zod schemas via reusable middleware.
Best for: API input validation
#express#zod
typescriptintermediate
Server Action Validation with Zod
Validate form data in server actions using Zod schemas with type-safe error handling.
Best for: contact forms
#nextjs#zod
typescriptintermediate
Environment Variable Validation with Zod
Validate environment variables at build time using Zod to catch misconfigurations early.
Best for: build-time validation
#nextjs#env
typescriptintermediate
OpenAI Chat Completion with Streaming
Stream GPT responses token-by-token using the OpenAI SDK with async iteration.
Best for: chatbot UI
#openai#streaming