Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json schema validation. How can I accept an array or null?

Tags:

json

c#

.net

We have implemented json schema validation (using newtonsoft) on our rest layer. It's really made a difference, but I have a question of possibility and how to.

For a specific property, the following is valid (according to the product owner):

.... choices: [] .......

.... choices: ["hello", "world"]

.... choices: null .....

here is a whittled down example of the json schema definition

{
   'description': 'myDescription',
   'type': 'object',
   'properties':
    {
     'name': {'type':'string', 'required': true},
     'description': {'type':'string'},
     'choices': {'type': 'array', 
         'items': {'type': 'string'}}
}

Obviously the first 2 examples pass validation, but the latter fails with "expecting an array" error.

The property is optional.

As an aside, if anyone has a good link to the full set of documentation on json schema definitions, I'd love to get it. I have not found a good single source, but I am sure there is one.

Thank you.

-r

like image 418
Roger Joys Avatar asked Jul 09 '13 17:07

Roger Joys


People also ask

How do you validate a JSON Schema?

The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. To get validation error messages, use the IsValid(JToken, JsonSchema, IList<String> ) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.

Which keyword would you use to configure a validator that validates all elements of an array?

The items keyword can be used to control whether it's valid to have additional items in a tuple beyond what is defined in prefixItems . The value of the items keyword is a schema that all additional items must pass in order for the keyword to validate.

What is allOf in JSON Schema?

By the definition of this keyword, it meant that the instance had to be valid against the current schema and all schemas specified in extends ; basically, draft v4's allOf is draft v3's extends .


1 Answers

You can specify an array of possible types like so;

"myProperty": { "type": [ "array", "null" ], "required":false }

The json will pass validation if "myProperty" is of any type in the type's array. I set required to false because you said this was an optional property, that will only make it pass if the property is not present in the json. If you have required set to false and the property is in the json but of the wrong type, validation will fail.

These are the best docs on json schemas that I know of; http://json-schema.org/latest/json-schema-validation.html The site lacks useful examples but any details that you need will be in the docs.

like image 148
evanmcdonnal Avatar answered Oct 20 '22 22:10

evanmcdonnal