使用 jsonschema 验证键在对象数组中是否具有唯一值?
Using jsonschema to validate that a key has a unique value within an array of objects?
如何使用 jsonschema 验证 JSON 在对象数组中,每个对象中的特定键必须是唯一的?例如,验证每个名称 k-v 对的唯一性应该失败:
"test_array": [
{
"Name": "name1",
"Description": "unique_desc_1"
},
{
"Name": "name1",
"Description": "unique_desc_2"
}
]
在 test_array 上使用 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"]
}
如何使用 jsonschema 验证 JSON 在对象数组中,每个对象中的特定键必须是唯一的?例如,验证每个名称 k-v 对的唯一性应该失败:
"test_array": [
{
"Name": "name1",
"Description": "unique_desc_1"
},
{
"Name": "name1",
"Description": "unique_desc_2"
}
]
在 test_array 上使用 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"]
}