Thanks to visit codestin.com
Credit goes to github.com

Skip to content

JSON schema override is not applied when schema is overridden #5499

@mattbasta

Description

@mattbasta

Test case:

const z = require('zod');

const schema = z.enum(['foo', 'bar']).meta({ foo: 'bar' });

const objectSchema = z.object({
  foo: schema.meta({ bar: 'zap' }),
  baz: z.array(schema),
});

const rendered = z.toJSONSchema(objectSchema, {
  io: 'output',
  override: ctx => {
    if (ctx.jsonSchema.type === 'string') {
      ctx.jsonSchema.thisShouldAlwaysAppear = 'in the output';
    }
  },
});

console.log(JSON.stringify(rendered, null, 2));

This outputs the following:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "foo": {
      "foo": "bar",
      "bar": "zap",
      "type": "string",
      "enum": [
        "foo",
        "bar"
      ],
      "thisShouldAlwaysAppear": "in the output"
    },
    "baz": {
      "type": "array",
      "items": {
        "foo": "bar",
        "type": "string",
        "enum": [
          "foo",
          "bar"
        ]
      }
    }
  },
  "required": [
    "foo",
    "baz"
  ],
  "additionalProperties": false
}

Notice that "thisShouldAlwaysAppear": "in the output" does not appear for the second instance.

This is using zod 4.1.13 and appears to be caused by this check:

https://github.com/colinhacks/zod/blob/main/packages/zod/src/v4/core/to-json-schema.ts#L828

Because the original schema is considered a parent, it is not overridden.

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