6

我一直在编写简单的 JSON 模式,但遇到了一个更复杂的 API 输入调用。我有一个可以采用 3 种非常不同类型的 JSON 的宁静结束路线:

本地主机/foo

可以采取:

{“类型”:“冰淇淋”,​​“圆锥”:“华夫饼”...}

或者

{“type”:“hot_dog”,“bun”:“wheat”...}

如果“type”键包含“ice_cream”,我只想看到键“cone”而不是键“bun”。同样,如果“type”包含“hot_dog”,我只想看到“bun”而不是“cone”。我知道我可以进行模式匹配以确保我只看到类型“ice_cream”或类型“hot_dog”,但如果该键设置为该值,我不知道如何强制要求某些其他字段。我看到有一个名为“依赖”的 json 模式字段,但我还没有找到任何关于如何使用它的好例子。

顺便说一句,我不确定这个输入 JSON 是否是好的形式(有效地重载了它所采用的 JSON 结构的类型),但我没有更改 api 的选项。

4

1 回答 1

3

我终于得到了一些关于这个的信息 - 事实证明你可以将几个不同的有效对象联合起来,如下所示:

{
    "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 死于某些无效输入,但它按预期接受了有效输入。

于 2011-02-25T01:37:39.483 回答