Skip to content

Instantly share code, notes, and snippets.

@christophemarois
Last active February 14, 2023 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christophemarois/34bb913cad54ddc309197df33339fde0 to your computer and use it in GitHub Desktop.
Save christophemarois/34bb913cad54ddc309197df33339fde0 to your computer and use it in GitHub Desktop.
Zod JSON Coercion
import * as z from 'zod'
function zJson <T extends z.ZodTypeAny> (schema: T) {
return z.string().transform((val, ctx) => {
try {
return JSON.parse(val)
} catch (err) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Invalid JSON',
})
return z.NEVER
}
}).pipe(schema)
}
// example
const env = z.object({
// Should be a json string that parses to an array of string urls
WEBHOOK_URLS: zJson(z.array(z.string().url()))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment