DevHubTools Robot Mascot
DevHubTools
Back to AI Agent Engineering
AI Agent EngineeringDifficulty: Beginner 4 min read

Get JSON You Can Trust from an LLM (with Zod Validation)

Ask a model for JSON, validate it with a Zod schema, and retry once with the error message, so your code only ever sees data with the right shape.

By Avnish Yadav

Prerequisites: Lesson: Your First LLM API Call Basic TypeScript
Published · Updated

Free-form text is fine for a chat window, but your code needs data: a category, a list of tags, a yes/no decision. In this lesson you'll ask a model for JSON, check it with a schema, and handle the times it gets it wrong, so the rest of your app only sees valid data.

You'll need: the setup from the previous lesson, TypeScript, and the zod package (npm install zod).

STEP 1 OF 8
STEP 01

Why "just ask for JSON" isn't enough

If you write "reply in JSON" in a prompt, you'll usually get JSON. But sometimes you'll get JSON wrapped in a sentence, a missing field, a number written as a string, or a value outside the list you allowed. Model output is untrusted input: treat it exactly like a form submitted by a stranger, and validate it before you use it.