Two way binding dependences based on enum value in json schema

可紊 提交于 2021-01-28 02:21:41

问题


I have a senior were I have to validate the schema for below json data.

{ 'userId': 123, 'userType': CUSTOMER }

Information about JSON: Were userId is an integer and the userType is enum['Customer','Admin','Guest']
So the issue is that I want to validate the JSON data from the JSON schema based on :

  1. If userId is present then userType is required.
  2. If userType ['Customer','Admin'] is present but userId is not then it should not validate the JSON data.
  3. But if the userType is ['Guest'] then their userId is required.

Here I have achieved point 1 but cannot achieve point 2 and 3 :

{
'type': 'object',
  'properties': {
     'user': {
         'type': 'integer',
         'minimum': 0
      },
     'userType': {
         'type': 'string',
         'enum': ['Customer','Admin','Guest'],
      }
   },
   'dependencies': {
       'userId': ['userType']
     }
}

Can anyone suggest me json schema solution for this ?


回答1:


I think you can solve it with with the property anyOf of json Schema, you can add multiple schemas to validate if the userType is Customer or Admin force one schema and if the user type is Guest force another one, like this:

{
  "anyOf": [
    {
      "type": "object",
      "properties": {
        "user": {
          "type": "integer",
          "minimum": 0
        },
        "userType": {
          "type": "string",
          "enum": [
            "Customer",
            "Admin"
          ]
        }
      }
    },
    {
      "type": "object",
      "properties": {
        "user": {
          "type": "integer",
          "minimum": 0
        },
        "userType": {
          "type": "string",
          "enum": [
            "Guest"
          ]
        },
        "userId": {
          "type": "string"
        }
      }
    }
  ]
}


来源:https://stackoverflow.com/questions/59963930/two-way-binding-dependences-based-on-enum-value-in-json-schema

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