Using Zod to Parse a JSON String

May 15th, 2024

·

1 min read

Using Zod to Parse a JSON String

I recently needed to parse a JSON string in TypeScript and validate the shape of the data. I discovered a neat utility that allowed me to handle both steps in one go.

import { z } from "zod";

const stringToJSONSchema = z.string().transform((str, ctx) => {
try {
return JSON.parse(str);
} catch (e) {
ctx.addIssue({ code: "custom", message: "Invalid JSON" });
return z.NEVER;
}
});

export const MyDataSchema = z.object({
foo: z.string(),
bar: z.number(),
});

const jsonString = '{"foo": "hello", "bar": 42}';

const result = stringToJSONSchema.pipe(MyDataSchema).safeParse(jsonString);