8000 v4: `z.toJSONSchema` incorrectly generates required properties for `default` values · Issue #4279 · colinhacks/zod · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

v4: z.toJSONSchema incorrectly generates required properties for default values #4279

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
pattobrien opened this issue Apr 25, 2025 · 2 comments

Comments

@pattobrien
Copy link

Description

Given the below schemas:

const foo = z.object({
  prop: z.string().default("fooPropDefault"),
});
const bar = z.interface({
  prop1: z.string().default("barProp1Default"),
  "prop2?": z.string().default("barProp2Default"),
});

const fooInputJsonSchema = z.toJSONSchema(foo, { io: "input" });
const fooOutputJsonSchema = z.toJSONSchema(foo, { io: "output" });
const barInputJsonSchema = z.toJSONSchema(bar, { io: "input" });
const barOutputJsonSchema = z.toJSONSchema(bar, { io: "output" });

When generating to JSON Schema (via z.toJSONSchema(...)), each optional field is expected to not be required in input schema, and required for the output schema.

Actual Result

// foo-input.json
{
  "type": "object",
  "properties": {
    "prop": {
      "type": "string",
      "default": "fooPropDefault"
    }
  },
  "required": [
    "prop" // incorrect
  ]
}

// bar-input.json
{
  "type": "object",
  "properties": {
    "prop1": {
      "type": "string",
      "default": "barProp1Default"
    },
    "prop2": {
      "type": "string",
      "default": "barProp2Default"
    }
  },
  "required": [
    "prop1" // incorrect
  ]
}

// bar-output.json
{
  "type": "object",
  "properties": {
    "prop1": {
      "type": "string",
      "default": "barProp1Default"
    },
    "prop2": {
      "type": "string",
      "default": "barProp2Default"
    }
  },
  "required": [
    "prop1",
    // missing prop2
  ]
}
@pattobrien pattobrien changed the title v4: z.toJSONSchema generates required properties for v4: z.toJSONSchema incorrectly generates required properties for default values Apr 25, 2025
@samchungy
Copy link
Contributor

Dupe of #4134

@pattobrien
Copy link
Author

Thanks @samchungy , closing as duplicate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants
0