Json 根据另一个对象的内容验证对象的值的架构

Json schema to validate object's values against content of another object

我正在尝试为文档创建 json 架构,其中某些对象中的字段值应根据同一文档中另一个对象中定义的枚举进行验证。

更具体地说,在下面的示例中,我希望能够使用 idvalues 定义“属性”(我应该能够在不同的 json 个文件)。 然后“对象”应该能够引用这些属性,因此 object.properties[i].id 必须与其中一个属性的 id 匹配,并且 object.properties[i].value 必须与为该属性定义的枚举值之一匹配 属性.

{
    "properties": [
        {
            "id": "SIZE",
            "values": ["small", "medium", "big"]
        },
        {
            "id": "MATERIAL",
            "values": ["wood", "glass", "steel", "plastic"]
        },
        {
            "id": "COLOR",
            "values": ["red", "green", "blue"]
        }
    ],

    "objects": [
        {
            "name": "chair",
            "properties": [
                {
                    "id": "SIZE",
                    "value": "small"
                },
                {
                    "id": "COLOR",
                    "value": "red"
                }
            ],
        },
        {
            "name": "table",
            "properties": [
                {
                    "id": "MATERIAL",
                    "value": "wood"
                }
            ]
        }
    ]
}

我试图创建 json 模式来验证这种结构,但无法描述对“属性”对象的内部字段的引用。我也查看了 standard 并没有找到实现目标的方法。

是否可以创建一个 json 模式来验证我的 json 文件?

有提案$data reference that almost allows to do it if you change your data structure a little bit to remove one level of indirection. It's is supported in Ajv(我是作者)

因此,如果您的数据是:

{
    "properties": {
        "SIZE": ["small", "medium", "big"],
        "MATERIAL": ["wood", "glass", "steel", "plastic"],
        "COLOR": ["red", "green", "blue"]
    },
    "objects": {
        "chair": {
            "SIZE": "small",
            "COLOR": "red"
        },
        "table": {
            "MATERIAL": "wood"
        }
    }
}

那么您的架构可能是:

{
    "type": "object",
    "properties": {
        "properties": {
            "type": "object",
            "additionalProperties": {
                "type": "array",
                "items": { "type": "string" }
            } 
        },
        "objects": {
            "type": "object",
            "additionalProperties": {
                "type": "object",
                "properties": {
                    "SIZE": {"enum": {"$data": "3/properties/SIZE"}},
                    "MATERIAL": {"enum": {"$data": "3/properties/MATERIAL"}},
                    "COLOR": {"enum": {"$data": "3/properties/MATERIAL"}}
                }
            }
        }
    }
}

并且它可以根据所有可能的属性列表动态生成。

使用您拥有的数据结构,您可以使用自定义关键字(如果验证器支持自定义关键字)或在 JSON 模式之外实现验证逻辑的某些部分。