Parsing a JSON string with zod #2215
Answered
by
JacobWeisenburger
alexgleason
asked this question in
Q&A
-
I'm tired of writing the same try-catch code over and over again to parse JSON strings, and would love to parse it with something zod-like so it fits with the rest of my code. This is what I've come up with so far: const jsonSchema = z.string().refine((value) => {
try {
JSON.parse(value);
return true;
} catch (_) {
return false;
}
}).transform((value) => JSON.parse(value)); Now I can do this: jsonSchema.parse('{"hello": "world"}') // {hello: "world"}
jsonSchema.safeParse('}') // {success: false, error: ZodError[...]}
jsonSchema.parse('}') // throws ZodError This works great, awesome! But is there a way I can avoid calling |
Beta Was this translation helpful? Give feedback.
Answered by
JacobWeisenburger
Mar 19, 2023
Replies: 2 comments 3 replies
Answer selected by
alexgleason
-
Just adding an alternative method of using const parseJsonPreprocessor = (value: any, ctx: z.RefinementCtx) => {
if (typeof value === 'string') {
try {
return JSON.parse(value);
} catch (e) {
ctx.addIssue({
code: ZodIssueCode.custom,
message: (e as Error).message,
});
}
}
return value;
}; This can then be reused in multiple schemas like.. const someObjectShapeSchema = z.object({
foo: 'bar',
});
const someObjectSchema = z.preprocess(parseJsonPreprocessor, someObjectShapeSchema);
// Use as you normally would
someObjectSchema.parse('{"foo":"bar"}'); // { foo: 'bar' } |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://github.com/JacobWeisenburger/zod_utilz#stringtojson