【问题标题】:writing more complex json schemas that have dependencies upon other keys编写依赖于其他键的更复杂的 json 模式
【发布时间】:2011-06-29 12:17:54
【问题描述】:

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

本地主机/foo

可以服用:

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

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

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

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

【问题讨论】:

  • 我知道这是一个老问题,但我想我只想提一下 v5 可能 有一个 switch 关键字可以完全满足您的需求。不过,我们将不得不等待实际的草稿......

标签: javascript json schema validation jsonschema


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多