[英]JSON schema, oneOf validation
My login endpoint can have "social" logins and "user" login so the body could either look like this: 我的登录端点可以具有“社交”登录名和“用户”登录名,因此正文可以如下所示:
user: {
email: 'test@gmail.com',
password: 'test'
}
Or like this: 或像这样:
authentication: {
provider: 'facebook',
token: 'abcd'
}
I want to create a JSON schema that validates either the first body, or the second body. 我想创建一个验证第一个正文或第二个正文的JSON模式。 I stumbled upon
oneOf
and this is what I have tried: 我偶然发现了
oneOf
,这就是我尝试过的:
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'
}
}
}
}]
}
However that gives me the following error: 但是,这给了我以下错误:
{
"keyword": "oneOf",
"dataPath": ".body",
"schemaPath": "#/properties/body/oneOf",
"params": {},
"message": "should match exactly one schema in oneOf"
}
Would be awesome if anyone can help me out with making a JSON schema setup for this. 如果有人可以帮助我为此做一个JSON模式设置,那将很棒。 Thanks
谢谢
You can do this with the oneOf
. 您可以使用
oneOf
进行此oneOf
。 Although I would use it differently. 虽然我会用不同的方式。
{
"$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"
}
}
}
}
}
}
}
With this, the two json are validated against the schema 有了这个,两个json会根据模式进行验证
{
"login": {
"authentication": {
"provider": "facebook",
"token": "abcd"
}
}
}
{
"login": {
"user": {
"email": "test@gmail.com",
"password": "test"
}
}
}
But if you try to put both of them in one, it will not validate 但是,如果您尝试将两者合而为一,它将无法验证
{
"login": {
"authentication": {
"provider": "facebook",
"token": "abcd"
},
"user": {
"email": "test@gmail.com",
"password": "test
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.