Using jsonschema to validate that a key has a unique value within an array of objects?

感情迁移 提交于 2019-12-08 03:00:00

问题


How do I validate JSON, with jsonschema, that within an array of objects, a specific key in each object must be unique? For example, validating the uniqueness of each Name k-v pair should fail:

"test_array": [
    {
        "Name": "name1",
        "Description": "unique_desc_1"
    },
    {
        "Name": "name1",
        "Description": "unique_desc_2"
    }
]

Using uniqueItems on test_array won't work because of the unique Description keys.


回答1:


I found the alternative method of using a schema that allows arbitrary properties. The only caveat is that JSON allows duplicate object keys, but duplicates will override their previous instances. The array of objects with the key "Name" can be converted to an object with arbitrary properties:

For example, the following JSON:

"test_object": {
    "name1": {
        "Desc": "Description 1"
    },
    "name2": {
        "Desc": "Description 2"
    }
}

would have the following schema:

{
    "type": "object",
    "properties": {
        "test_object": {
            "type": "object",
            "patternProperties": {
                "^.*$": {
                    "type": "object",
                    "properties": {
                        "Desc": {"type" : "string"}
                    },
                    "required": ["Desc"]
                }
            },
            "minProperties": 1,
            "additionalProperties": false
        }
    },
    "required": ["test_object"]
}


来源:https://stackoverflow.com/questions/49886837/using-jsonschema-to-validate-that-a-key-has-a-unique-value-within-an-array-of-ob

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!