如何使用jsonschema验证JSON,即在对象数组中,每个对象中的特定键必须是唯一的?例如,验证每个Name k-v对的唯一性应该失败:
"test_array": [
{
"Name": "name1",
"Description": "unique_desc_1"
},
{
"Name": "name1",
"Description": "unique_desc_2"
}
]
由于描述码的唯一性,在test_数组上使用uniqueItems将不起作用。
我找到了使用允许任意属性的模式的替代方法。唯一的警告是JSON允许重复的对象键,但是重复的对象键将覆盖它们以前的实例。具有键"Name"的对象数组可以转换为具有任意属性的对象:
例如,以下JSON:
"test_object": {
"name1": {
"Desc": "Description 1"
},
"name2": {
"Desc": "Description 2"
}
}
将具有以下架构:
{
"type": "object",
"properties": {
"test_object": {
"type": "object",
"patternProperties": {
"^.*$": {
"type": "object",
"properties": {
"Desc": {"type" : "string"}
},
"required": ["Desc"]
}
},
"minProperties": 1,
"additionalProperties": false
}
},
"required": ["test_object"]
}