Replies: 3 comments 22 replies
-
Are you picturing a command-line tool that outputs a Zod schema given some arbitrary JSON input?
Something like that? I'm not aware of anything like that, but there are projects output JSON schemas so perhaps you could use something like https://github.com/StefanTerdell/zod-to-json-schema as inspiration for making such a tool? |
Beta Was this translation helpful? Give feedback.
-
Here you go :) import { format } from "prettier";
const jsonToZod = (obj: any): string => {
const parse = (obj: any): string => {
switch (typeof obj) {
case "string":
return "z.string()";
case "number":
return "z.number()";
case "bigint":
return "z.number().int()";
case "boolean":
return "z.boolean()";
case "object":
if (Array.isArray(obj)) {
const options = obj
.map(parse)
.reduce(
(acc, curr) => (acc.includes(curr) ? acc : [...acc, curr]),
[]
);
if (options.length === 1) {
return `z.array(${options[0]})`;
} else if (options.length > 1) {
return `z.array(z.union([${options}]))`;
} else {
return "z.array(z.unknown())";
}
}
return `z.object({${Object.entries(obj)
.map(([k, v]) => `${k}:${parse(v)}`)
}})`;
case "undefined":
return "z.undefined()";
case "function":
return "z.function()";
case "symbol":
default:
return "z.unknown()";
}
};
return format(`const schema=${parse(obj)}`, { parser: "babel" });
}; |
Beta Was this translation helpful? Give feedback.
-
Reposting my answer so it doesn't get buried in the thread Here's a page where you can paste your JSON or JS objects (JSON5) Or if you prefer a package/CLI If anyone wants to maintain it, let me know and I'll transfer the repos. [edit: borken link] |
Beta Was this translation helpful? Give feedback.
-
Hi, I am just starting with zod, looks amazing.
The one tool I am missing and would dearly need is something that can generate a schema from a given json object. Doesn't have to be extra smart (but some intelligence would be great).
Is there any such tool around? I will eventually be using this so much that it might save time if I have to do a rudimentary one.
To be clear, I don't need that dynamically, just static conversion to get started on the schema.
Beta Was this translation helpful? Give feedback.
All reactions