开发者

writing more complex json schemas that have dependencies upon other keys

开发者 https://www.devze.com 2023-02-11 00:18 出处:网络
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:

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 s开发者_运维百科ee 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号