zod icon indicating copy to clipboard operation
zod copied to clipboard

v4(toJSONSchema): Pattern info lost when using multiple patterns

Open samchungy opened this issue 10 months ago • 0 comments

import { toJSONSchema, z } from 'zod/v4';

const a = z.string().startsWith('foo').includes('bar');

console.log(JSON.stringify(toJSONSchema(a), null, 2));

Results in:

{
  "type": "string",
  "pattern": "bar",
  "$schema": "https://json-schema.org/draft/2020-12/schema"
}

Which is not incorrect but we lose info on the other pattern. It looks like we currently only consider 1 pattern: https://github.com/colinhacks/zod/blob/29aba82eb2131e979723cecc49d4cfa901386fd6/packages/zod/src/v4/core/schemas.ts#L290-L294

We could potentially make use of allOf in this scenario:

eg.

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "allOf": [
	{
	  "type": "string",
	  "pattern": "bar",
	},
	{
	  "type": "string",
	  "pattern": "^foo"
    }
  ]
}

samchungy avatar May 23 '25 06:05 samchungy