writing more complex json schemas that have dependencies upon other keys

有些话、适合烂在心里 提交于 2019-12-22 05:33:28

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/5036366/writing-more-complex-json-schemas-that-have-dependencies-upon-other-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!