JSON Schema: validate a number-or-null value

Adam Matan picture Adam Matan · Mar 21, 2014 · Viewed 27.4k times · Source

Is there a way to enable a JSON schema property to be either a number or null?

I am building an API which contains a heading attribute. Can be a number between 0 (inclusive) and 360 (exclusive), or null, so the following inputs are OK:

{"heading": 5}
{"heading": 0}
{"heading": null}
{"heading": 12}
{"heading": 120}
{"heading": null}

And the following inputs are erroneous:

{"heading": 360}
{"heading": 360.1}
{"heading": -5}
{"heading": false}
{"heading": "X"}
{"heading": 1200}
{"heading": false}

Addendum:

anyOf is clearly the right answer. Adding the full schema for clarity.

Schema

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "additionalProperties": false,
    "properties": {
      "heading": {
        "anyOf": [
          {"type": "number"},
          {"type": "null"}
        ]
      }
    }
}

Answer

fiddur picture fiddur · Mar 23, 2014

In draft-04, you would use the anyOf directive:

{
  "anyOf": [
    {
      "type": "number",
      "minimum": 0,
      "maximum": 360,
      "exclusiveMaximum": true
    },
    {
      "type": "null"
    }
  ]
}

You could also use "type": ["number", "null"] as Adam suggests, but I think anyOf is cleaner (as long as you use a draft-04 implementation), and ties the minimum and maximum declaration to the number explicitly.

Disclaimer: I don't know anything about the python implementation, my answer is about json schema.