Writing more complex json schemes with dependencies on other keys

I wrote simple JSON schemes, but I ran into an API input call, which is a bit more complicated. I have one calm final route that can accept 3 very different JSON types:

local / foo

may accept:

{"type": "ice_cream", "cone": "waffle" ...}

or

{"type": "hot_dog", "bun": "wheat" ...}

If the "type" key contains "ice_cream", I just want to see the cone key, not the key bun. Similarly, if "type" contains "hot_dog", I want to see a "bun" rather than a "cone". I know that I can match patterns to make sure that I only ever see the type "ice_cream" or the type "hot_dog", but I do not know how to force some other fields if this key is set to this value. I see that there is a json schema field called a dependency, but I have not found good examples of how to use it.

By the way, I'm not sure if this JSON input is a good form (overloading the type of JSON structure it takes is efficient), but I have no way to change the api.

+6
json javascript validation schema jsonschema
source share
1 answer

Finally, I got some information about this - it turns out that you can do the union of several different objects that would be true:

{ "description" : "Food", "type" : [ { "type" : "object", "additionalProperties" : false, "properties" : { "type" : { "type" : "string", "required" : true, "enum": [ "hot_dog" ] }, "bun" : { "type" : "string", "required" : true }, "ketchup" : { "type" : "string", "required" : true } } }, { "type" : "object", "additionalProperties" : false, "properties" : { "type" : { "type" : "string", "required" : true, "enum": [ "ice_cream" ] }, "cone" : { "type" : "string", "required" : true }, "chocolate_sauce" : { "type" : "string", "required" : true } } } ] } 

I'm still not sure if this is valid JSON, as my Schemavalidator is dying from incorrect input, but it accepts valid input as expected.

+3
source share

All Articles