13

I'm using the play-json-schema-validator and want to set up an integration test with scala in order to check an API's JSON response schema.

Certain fields of the response are nullable and I want to validate for that. So some field can be either a string or null yet it can never be a number.

Playing around on its playground I want to validate for an array of objects that each object's name property is either a string or null.

I came up with this schema:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Product set",
  "type": "array",
  "items": {
    "title": "Product",
    "type": "object",
    "properties": {
      "name": {
        "type": ["string", null]
      }
    }
  }
}

Yet though it validates the string and null case, I now get a false positive for numbers. I was expecting an error for this json, yet it validates:

[
  {
    "name": "Red anger"
  },
  {
    "name": null
  },
  {
    "name": 13
  }
]

How to declare a field of a type as nullable using schema validator?

2 Answers 2

14

Enquote the null in the schema:

"type": ["string", "null"]

You can read about that in the json schema validation documentation, i.e.:

6.1. Validation Keywords for Any Instance Type

6.1.1. type

The value of this keyword MUST be either a string or an array. If it is an array, elements of the array MUST be strings and MUST be unique.

String values MUST be one of the six primitive types ("null", "boolean", "object", "array", "number", or "string"), or "integer" which matches any number with a zero fractional part.

An instance validates if and only if the instance is in any of the sets listed for this keyword.

4

The type attribute of the schema does not accept arrays but only a single type at the time: "string", "null"... and as you pointed out, the types should be strings so instead of null => "null"

If you want to check multiple types for a single field you need to use

anyOf, oneOf, allOf

Here is an example working with your input

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Product set",
  "type": "array",
  "items": {
    "title": "Product",
    "type": "object",
    "properties": {
      "name": {
        "anyOf": [
            {"type":"string"},
            {"type":"null"},
            {"type":"number"}
        ]
      }
    }
  }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.