voxpupuli / json-schema

Ruby JSON Schema Validator
MIT License
1.52k stars 241 forks source link

Allow type or null? #441

Closed Andrew-Max closed 4 years ago

Andrew-Max commented 4 years ago

I have a schema:

{
    type: "object",
    properties: {
      product_id:      { type: "string" },
      tip_description: { type: "string" },
      core_diameter:   { type: "number" },
      outer_diameter:  { type: "number" },
      aperature:       { type: "number" },
    },
    required: []
  }

Note nothing is required here and the only way to set an undefined is with null

So it seems to me like this should be a valid entry

{
  "product_id": null,
  "tip_description": null,
  "core_diameter": null,
  "outer_diameter": null,
  "aperature": null
}

But validation fails telling me that it expected string or numeric types, not null. I explicitly do not want to trim out null properties, I want them to be saved as present with a value of null so it is clear to end users which properties exist.

Is there any way to accomplish this?

stefanosx commented 4 years ago

I run into the same issue, and I solved the issue by adding an array as a type(Not sure if it is the best solution).

So you can change your schema to look like this:

{
    type: "object",
    properties: {
      product_id:      { type: ["string", "null"] },
      ...
    },
    required: []
  }

And that should work fine.

Andrew-Max commented 4 years ago

@stefanosx clever solution. It's hackier than I'd like for something I'm putting into production but it does solve my immediate issue for now. Thanks!