【问题标题】:json-schema v4 how-to implements enums depending on enums?json-schema v4 如何根据枚举实现枚举?
【发布时间】:2015-05-30 18:10:37
【问题描述】:

使用json-editor 并查看answer,我正在尝试使用json-schema v4 执行以下操作:

使用根属性选择['clothing', 'accessory'] 的两个类别之一,这将确定material 属性的枚举值。

我试图解决的案例有多个枚举属性,具体取决于category-value。

伪代码示例:

{
    "type": "object",
    "Title": "Products",
    "definitions": {
        "clothing": {
            "materials": ["yak", "merino"]
        },
        "accessories": {
            "materials": ["brass", "silver"]
        }
    },
    "properties": {
        "productType": {
            "type": "string",
            "enum": [
                "clothing",
                "accessories"
            ]
        },
        "materials": {
            "type": "array",
            "title": "Materials",
            "items": {
                "type": "string",
                "title": "Material",
                "enum": [
                    {"$ref" : "#definitions/{{productType}}/materials"}
                ]
            }
        }
    } 
}

关于如何构建它有什么建议吗?

【问题讨论】:

    标签: javascript json jsonschema


    【解决方案1】:

    在这种情况下,使用oneOf 子句为第一级定义类型可能更容易,并且只在嵌套级别使用枚举。比如:

    "definitions" : {
        "materialType" : {
            "oneOf" : [{
                    "$ref" : "#definitions/clothing"
                }, {
                    "$ref" : "#definitions/accesories"
                }
            ]
        },
        "clothing" : {
            "materials" : {
                "enum" : ["yak", "merino"]
            }
        },
        "accessories" : {
            "materials" : ["enum" : ["brass", "silver"]]
        }
    }
    

    然后你像这样消费materialType

    "materials": {"$ref":"#definitions/materialType"}
    

    如果您还想在对象实例中编码materialType,那么您可以像这样添加另一个属性枚举,但我不建议这样做:

    "clothing" : {
        "materials" : {
            "enum" : ["yak", "merino"]
        },
        "kind": {"enum" : ["clothing"]}
    }
    

    【讨论】:

    • 很好,但主要问题是我有多个枚举,具体取决于类别。因此,除了材料之外,还会有一个子类别,例如["ring", "necklace"] 用于配饰,["scarf", "beanie"] 用于服装。那么我会复制“oneOf”中的模式,可以这么说,还是尝试更直接地访问枚举值,也许是动态的? (哦,谢谢你的回答)
    • 您可以将枚举值添加到依赖模式中,例如:"clothing": {"materials":{"enum":["yak",merino"]},"subcategory": {"enum":["ring","necklace"]},"accesory":{"enum":["scarf","beanie"]}} 但你开始突破 json-schema 的极限,它验证结构,而不是数据。另一个更简单的选择是将数据验证作为服务扩展(在代码中)。这也将简化您的 json-schema 生命周期管理。
    • 如果 Json Schema 只验证结构,而不验证数据,那么枚举类型本身显然超出了该边界。您要么必须取出枚举并将其保留为数组,要么提供一种方法来干燥枚举。
    • 我认为 enum 更像是对值类型的约束,例如数字、字符串、对象、数组... enum = "collection of listed items"。
    • 不明白“那你就这样消费materialType:”这一步……如何在伪代码示例中实现这个?
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2023-02-06
    • 1970-01-01
    • 2020-07-19
    • 2010-09-11
    • 1970-01-01
    相关资源
    最近更新 更多