Note
Using Zod to Parse a JSON String
Parse a JSON string and validate the resulting data shape in one composable Zod schema.
- typescript
- zod
- validation
I recently needed to parse a JSON string in TypeScript and validate the shape of the resulting data. I found a small utility from zod_utilz that handles both steps in one schema pipeline.
import { z } from "zod";
const stringToJSONSchema = z.string().transform((value, context) => {
try {
return JSON.parse(value);
} catch {
context.addIssue({ code: "custom", message: "Invalid JSON" });
return z.NEVER;
}
});
const MyDataSchema = z.object({
foo: z.string(),
bar: z.number(),
});
const jsonString = '{"foo": "hello", "bar": 42}';
const result = stringToJSONSchema.pipe(MyDataSchema).safeParse(jsonString);
The transform handles JSON syntax errors. Piping its output into MyDataSchema then validates the parsed value before the caller can use it.