JSON模式,oneOf验证

时间:2017-08-15 03:49:36

标签: json validation jsonschema

我的登录端点可以进行“社交”登录和“用户”登录,因此正文可能如下所示:

authentication: {
  provider: 'facebook',
  token: 'abcd'
}

或者像这样:

oneOf

我想创建一个JSON模式来验证第一个主体或第二个主体。我偶然发现了body: { oneOf: [{ properties: { user: { type: 'object', required: [ 'email', 'password' ], email: { type: 'string', format: 'email' }, password: { type: 'string', minLength: 6, maxLength: 32 } }, } }, { properties: { authentication: { type: 'object', required: [ 'provider', 'token' ], provider: { type: 'string', enum: ['facebook'] }, token: { type: 'string' } } } }] } ,这就是我所尝试过的:

    {
        "keyword": "oneOf",
        "dataPath": ".body",
        "schemaPath": "#/properties/body/oneOf",
        "params": {},
        "message": "should match exactly one schema in oneOf"
    }

然而,这给了我以下错误:

{{1}}

如果有人可以帮助我为此设置JSON架构,那将是非常棒的。感谢

1 个答案:

答案 0 :(得分:2)

您可以使用oneOf执行此操作。虽然我会以不同的方式使用它。

 {
   "$schema": "http://json-schema.org/schema#",
   "type": "object",
   "properties": {
     "login": {
       "oneOf": [
         {
           "required": [
             "user"
           ]
         },
         {
           "required": [
             "authentication"
           ]
         }
       ],
       "type": "object",
       "properties": {
         "user": {
           "type": "object",
           "properties": {
             "email": {
               "type": "string"
             },
             "password": {
               "type": "string"
             }
           }
         },
         "authentication": {
           "type": "object",
           "properties": {
             "email": {
               "type": "string"
             },
             "password": {
               "type": "string"
             }
           }
         }
       }
     }
   }
 }

这样,两个json就会根据模式

进行验证
 {
   "login": {
     "authentication": {
       "provider": "facebook",
       "token": "abcd"
     }
   }
 } 

 {
   "login": {
     "user": {
       "email": "test@gmail.com",
       "password": "test"
     }
   }
 }

但是如果你试图将它们都放在一个中,它就不会验证

 {
   "login": {
     "authentication": {
       "provider": "facebook",
       "token": "abcd"
     },
     "user": {
       "email": "test@gmail.com",
       "password": "test
     }
   }
 }