How to define a JSON schema that requires at least one of many properties

前端 未结 2 786
余生分开走
余生分开走 2021-01-03 17:22

I would like to know if I can define a JSON schema (draft 4) that requires at least one of many properties possible for an object. I already know of allOf,

相关标签:
2条回答
  • 2021-01-03 17:56

    You may use minProperties: number (and maxProperties: number if needed). That would shorten the schema definition:

    {
         type: "object",
         minProperties: 1,
         properties: [/* your actual properties definitions */],
    }
    

    Link to documentation: https://json-schema.org/understanding-json-schema/reference/object.html#size

    0 讨论(0)
  • 2021-01-03 18:09

    To require at least one of a set of properties, use required inside a series of anyOf options:

    {
        "type": "object",
        "anyOf": [
            {"required": ["id"]},
            {"required": ["email"]}
            // any other properties, in a similar way
        ],
        "properties": {
            // Your actual property definitions here
        }
    {
    

    If any of the properties you want is present ("id", "email"), then it will pass the corresponding option in allOf.

    0 讨论(0)
提交回复
热议问题