Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing more complex json schemas that have dependencies upon other keys

I've been writing simple JSON schemas but I ran into an API input call that is a bit more complex. I have one restful end route that can take 3 very different types of JSON:

localhost/foo

can take:

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

or

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

If the "type" key contains "ice_cream", I only ever want to see the key "cone" and not the key "bun". Similiarly if "type" contains "hot_dog" I only want to see "bun" and not "cone". I know I can pattern match to make sure I only ever see type "ice_cream" or type "hot_dog", but I don't know how to force the requirement of certain other fields if that key is set to that value. I see that there is a json schema field called "dependency" but I haven't found any good examples on how to use it.

BTW, I'm not sure if this input JSON is good form (overloading the type of JSON structure it takes, effectively), but I don't have the option of changing the api.

like image 674
V_H Avatar asked Feb 18 '11 00:02

V_H


1 Answers

I finally got some information about this - it turns out you can make a union of several different objects that are valid like so:

{
    "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, since my Schemavalidator dies on some invalid input, but it accepts the valid input as expected.

like image 108
V_H Avatar answered Oct 30 '22 02:10

V_H