14

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

0

2 Answers 2

27

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. This solved the issue. I also discovered 'type':'any' which was also useful in some of our properties where the type was dependent on some other attributes of the payload.
In further googling, I found this which was also helpful and had some better examples: tools.ietf.org/html/draft-zyp-json-schema-03
@RogerJoys yeah I've looked at that. If you post other json schema questions on SO I'll likely answer them. They're pretty under utilized so there isn't a ton of information on them but I've been using them for a bit so I know at least all of the basics plus a few other tricks.
This answer is for draft 3. in 4 and later the requirements are an array that go on the parent element. github.com/json-schema/json-schema/wiki/ChangeLog#required
1

Have you tried making the default value for choices be []?

I am assuming, since you said the property is optional, that you are using the optional parameter syntax in C# or am I incorrect?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.