Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate for nullable types using json schema validator?

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?

like image 712
k0pernikus Avatar asked Dec 01 '17 11:12

k0pernikus


2 Answers

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.

like image 95
k0pernikus Avatar answered Oct 23 '22 15:10

k0pernikus


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"}
        ]
      }
    }
  }
}
like image 29
Davidacce Avatar answered Oct 23 '22 15:10

Davidacce