json schema object property constraints

北战南征 提交于 2021-01-28 19:53:43

问题


In my schema I have an array of phone objects. Each object has a "status" property, which can be one of three values: "Primary", "Active" and "Not-in-use".

I want to set the following constraint: If the number of phone objects > 0 then exactly one must have status="Primary"

Is this possible with json schema? If so, how?


回答1:


This schema is pretty close to what you want. The only restriction is that the "Primary" phone number needs to be the first item in the array.

You might be able to get "Primary" to be anywhere in the array with some creative use of not. I'll update the answer if I figure it out.

{
  "type": "object",
  "properties": {
    "phoneNumbers": {
      "type": "array",
      "items": [{ "$ref": "#/definitions/primaryPhone" }],
      "additionalItems": { "$ref": "#/definitions/additionalPhone" }
    }
  },
  "definitions": {
    "phone": {
      "type": "object",
      "properties": {
        "label": { "type": "string" },
        "number": { "type": "string" }
      },
      "required": ["label", "number", "status"]
    },
    "primaryPhone": {
      "allOf": [{ "$ref": "#/definitions/phone" }],
      "properties": {
        "status": { "enum": ["Primary"] }
      }
    },
    "additionalPhone": {
      "allOf": [{ "$ref": "#/definitions/phone" }],
      "properties": {
        "status": { "enum": ["Active", "Not-in-use"] }
      } 
    }
  }
}


来源:https://stackoverflow.com/questions/35683723/json-schema-object-property-constraints

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