Skip to content

[v4]: .default breaks optional fields in json schema #4697

@dariozachow

Description

@dariozachow

When using the z.toJSONSchema optional fields will be marked as required when using the .default on this field.

Example:

z.toJSONSchema(
    z.object({
      test: z.string().optional().default('abc')
    })
  )

will result in the following json schema:

  '$schema': 'https://json-schema.org/draft/2020-12/schema',
  type: 'object',
  properties: { test: { default: 'abc', type: 'string' } },
  required: [ 'test' ],
  additionalProperties: false
}

Even though test is not required, because its marked as optional.

When using optional without default works perfectly fine:

  z.toJSONSchema(
    z.object({
      test: z.string().optional()
    })
  )

will become

{
  '$schema': 'https://json-schema.org/draft/2020-12/schema',
  type: 'object',
  properties: { test: { type: 'string' } },
  additionalProperties: false
}

Using zod 3.25.64

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions