我如何在 json 架构中指定某个 属性 是必需的并且还必须包含特定值?

How can I specify in a json schema that a certain property is mandatory and also must contain a specific value?

我想为不同的场景创建多个 json 模式。

对于场景 1,我想说明:

a) 属性“draftenabled”的值必须为 true。

b) 属性“draftenabled”确实存在。

我检查过这个post 并尝试了以下

我试图验证这个 json

{
    "$schema": "./test-schema.json",
    "draftenabled": false,
    "prefix": "hugo"
}

使用我在 Visual Studio 代码中创建的模式测试-schema.json。

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "properties": {
        "$schema": {
            "type": "string"
        },
        "draftenabled": {
            "type": "boolean"
        },
        "prefix": {
            "type": "string"
        }
    },
    "additionalItems": false,
    "contains": {
        "properties": {
            "draftenabled": {
                "const": true
            }
        },
        "required": [
            "draftenabled"
        ]
    }
}

我预计会出现错误,因为 draftenabled 的值为 false 而不是 true。

关于关键字如何应用于不同类型的实例(数据),似乎存在一些混淆。

  • properties 仅适用于对象
  • additionalItemscontains只适用于数组

由于您的实例是一个对象,additionalItemscontains 将被忽略。

根据你对你想要的描述,我会做如下事情:

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "properties": {
        "$schema": {
            "type": "string"
        },
        "draftenabled": {
            "const": "true"
        },
        "prefix": {
            "type": "string"
        }
    },
    "required": [
        "draftenabled"
    ]
}

这会将您在 contains 中的定义移动到主架构中。你说对了一点,只是在错误的地方。


您还提到这是“场景 1”。如果还有其他场景,我建议为每个场景创建这样的模式,然后将它们全部包装在 oneOfanyOf:

{
    "oneOf": [
        { <scenario 1> },
        { <scenario 2> },
        ...
    ]
}