首页 > 解决方案 > 如何在 json 模式中指示动态添加支持?

问题描述

刚开始使用 jsonschema。我想描述一个属性的对象集合,其中可能不知道先验的键。

这是我的出发点:

                "tx_properties": {
                    "type": "object",
                    "anyOf": [
                        {
                            "required": [
                                "original_msg"
                            ]
                        }
                    ],
                    "properties": {
                        "original_msg": {
                            "type": "string"
                        }
                    }
                }
            }

我希望能够验证更多属性的添加,因为这些属性tx_properties可能具有不同的类型,但在架构定义时未知。

例如,我可能在 json 中有:

"tx_properties": {
    "original_msg": "foo",
    "something_else": "bar",
    "or_something_numeric": 172,
    "or_even_deeper_things": {
        "fungible": false,
    }
}

作为一个n00b,我有点坚持如何做到这一点。的使用anyOne是我认为至少在最终解决方案中需要的。

标签: jsonschema

解决方案


正如@Evert 所说,可用于指示除关键字 (and ) 中"additionalProperties": false列出的属性外,不允许使用其他属性。如果省略,则行为就像模式所说的一样(即,允许附加属性)。propertiespatternPropertiesadditionalProperties"additionalProperties": true

另请注意, at 的值additionalProperties不必是布尔值:它本身可以是子模式,以允许您根据其值有条件地允许其他属性。

参考:https ://json-schema.org/understanding-json-schema/reference/object.html#additional-properties


推荐阅读