StefanTerdell / zod-to-json-schema

Converts Zod schemas to Json schemas
ISC License
854 stars 67 forks source link

Date fields accepted by zod schema are not accepted by JSON schema generated from it #110

Closed matthew-kaye closed 5 months ago

matthew-kaye commented 5 months ago

Hello @matthew-kaye, thanks for opening an issue.

The behavior you describe makes sense to me. z.date() represents the JS Date class, which by default is serialized to JSON as a date-time string, thus matching z.string().datetime().

Feel free to reopen the issue if you don't agree!

I'm not sure I do agree actually sorry 😅 Since a zod schema for z.date() would allow a data field like "2024-01-01" but a JSON schema requiring a date-time would not. It seems normal to me to expect that data which would pass the zod schema would also be accepted by the JSON schema generated from it

image

Hope that makes sense! If alternatively you know of a way to ensure the generated schema accepts a date field then do let me know - I'm keen to actually check it's a valid date with a format field rather than attempt a long regex

Original issue

StefanTerdell commented 5 months ago

Hmm, ok, I understand the issue. I'm usually more focused on describing the output of data validated through Zod, which is ironic given we can only serialize the input expectations... I guess in this case another(!) strategy option might be useful to be able to generate something like

{
  "type": "string",
  "anyOf": [
    {
      "format": "date",
    },
    {
      "format": "date-time"
    },
    {
      "format": "time"
    }
  ]
}
matthew-kaye commented 5 months ago

Hmm, ok, I understand the issue. I'm usually more focused on describing the output of data validated through Zod, which is ironic given we can only serialize the input expectations... I guess in this case another(!) strategy option might be useful to be able to generate something like

{
  "type": "string",
  "anyOf": [
    {
      "format": "date",
    },
    {
      "format": "date-time"
    },
    {
      "format": "time"
    }
  ]
}

Thanks for understanding, that would certainly solve all my issues if that was the output! Though I don't know if having time as a possible format is maybe too lenient?

StefanTerdell commented 5 months ago

@matthew-kaye Mind checking out #111?

matthew-kaye commented 5 months ago

Ah sorry went straight to theatre after 5:30, will test it out though!