【问题标题】:Two way binding dependences based on enum value in json schemajson模式中基于枚举值的两种方式绑定依赖
【发布时间】:2020-01-29 09:21:31
【问题描述】:

我有一个大四学生,我必须验证以下 json 数据的架构。

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

关于 JSON 的信息:userId 是整数,userType 是枚举['Customer','Admin','Guest']
所以问题是我想验证来自 JSON 模式的 JSON 数据,基于:

  1. 如果存在userId,则需要userType
  2. 如果存在 userType ['Customer','Admin'] 但不存在 userId,则不应验证 JSON 数据。
  3. 但是如果userType['Guest'] 那么他们的userId 是必需的。

这里我已经达到了第 1 点,但无法达到第 2 点和第 3 点:

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

谁能为此建议我 json 架构解决方案?

【问题讨论】:

    标签: javascript json jsonschema json-schema-validator


    【解决方案1】:

    我认为您可以使用 json Schema 的属性anyOf 来解决它,您可以添加多个模式来验证userTypeCustomer 还是Admin 强制一个模式以及用户类型是否为@ 987654325@强制另一个,像这样:

    {
      "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"
            }
          }
        }
      ]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-16
      • 2017-06-03
      • 2016-03-09
      • 2017-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多