编写更复杂的json模式,这些模式依赖于其他键 [英] writing more complex json schemas that have dependencies upon other keys
问题描述
我一直在编写简单的JSON模式,但我遇到了一个更复杂的API输入调用。我有一个宁静的结束路线,可以采用3种非常不同类型的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
localhost/foo
can拿:
{type:ice_cream,cone:waffle...}
{ "type" : "ice_cream", "cone" : "waffle" ...}
或
{type:hot_dog,bun:wheat......}
{"type" : "hot_dog", "bun" : "wheat" ...}
如果type键包含ice_cream,我只想看到键cone而不是键bun。同样,如果type包含hot_dog,我只想看bun而不是cone。我知道我可以模式匹配,以确保我只看到类型ice_cream或键入hot_dog,但我不知道如果该键设置为该值,如何强制某些其他字段的要求。我看到有一个名为依赖的json架构字段,但我没有找到关于如何使用它的任何好例子。
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,我不确定如果这个输入JSON是好的形式(有效地重载它所采用的JSON结构的类型),但是我没有更改api的选项。
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
}
}
}
]
}
我仍然不确定这是否是有效的JSON,因为我的Schemavalidator死了一些无效的输入,但它按预期接受有效输入。
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.
这篇关于编写更复杂的json模式,这些模式依赖于其他键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!