Reputation: 988
My test data-
const testData = {
"one-level": {
"title": "Hello"
},
"two-level": {
"one-level": {
"title": "Hi"
}
}
}
"title": string
.I tried unions, lazy and recursive etc with no luck. My attempt-
import { z } from "zod";
const standardSchema = z.object({
"title": z.string()
})
const oneLevelSchema = standardSchema;
const nestedSchema = z.object({
"title": z.string(),
child: z.lazy(() => oneLevelSchema)
})
const testSchema = z.record(z.union([standardSchema, nestedSchema])
const isValid = testSchema.safeParse(testData);
if (!isValid.success) {
console.log("error")
} else {
console.log("success")
}
I can get either one of these (one or two level) to work but not both. I would think this would be simple or
or union
, but no luck.
Upvotes: 0
Views: 21
Reputation: 848
Update your schema as per below:
const jsonSchema = z.lazy(() =>
z.union([z.object({ title: z.string() }), z.record(jsonSchema)])
);
For more information, you can check the docs
Upvotes: 0