WhatisSober
WhatisSober

Reputation: 988

Validate one level or n level data structure using zod schema

My test data-

const testData = {
 "one-level": {
   "title": "Hello"
 },
 "two-level": {
   "one-level": {
    "title": "Hi"
   }
  }
 }

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

Answers (1)

Pinal Tilva
Pinal Tilva

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

Related Questions