typescriptintermediate

LLM JSON Output Parser

Parse and validate JSON responses from LLMs with retry logic and schema enforcement using Zod.

typescript
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.