I'm finding it difficult to understand how to validate different types of responses with different set of validation. I'm just put an example code and that might make sense then trying to explain it.
我发现很难理解如何使用不同的验证集来验证不同类型的响应。我只是放了一个示例代码然后再解释它。
Example dataset:
示例数据集:
responses: [
{ type: 'user', age: 5 }
{ type: 'admi', auth: {...} }
]
json schema sample:
json模式示例:
{
"definitions": {
"user": {
"type": "object",
"properties": {
"type": { "type": "string" },
"age": { "type": "number" }
}
"required": ["age"]
},
"admin": {
"type": "object",
"properties": {
"type": { "type": "string" },
"auth": { "type": "object" }
}
"required": ["auth"]
}
},
"responses": {
"type": "array",
"anyOf": [
{ "$ref": "#/definitions/user" }
{ "$ref": "#/definitions/admi" }
]
}
}
How can these be validated depending on type (not string, number
, but 'user', 'admi'
)?
如何根据类型(不是字符串、数字,而是'user'、'admi')对它们进行验证?
1 个解决方案
#1
1
You'll be looking for validation keywords whcih apply to strings or any types in your instance. In the latest version of JSON Schema, you can find const
.
您将寻找适用于字符串或实例中的任何类型的验证关键字whcih。在最新版本的JSON模式中,您可以找到const。
You would add a const key word as follows for your user definition...
您将为您的用户定义添加一个const关键字如下…
...
"user": {
"type": "object",
"properties": {
"type": { "type": "string", "const": "user" },
"age": { "type": "number" }
}
"required": ["age"]
},
...
If const
isn't available to you because you need to use an older version of JSON Schema, you could use enum
which is practically the sam but you woule encase the string "user" inside an array as the value for the enum
key word.
如果const对您不可用,因为您需要使用JSON模式的旧版本,您可以使用enum(实际上是sam),但您可以将数组中的字符串“user”作为enum关键字的值。
#1
1
You'll be looking for validation keywords whcih apply to strings or any types in your instance. In the latest version of JSON Schema, you can find const
.
您将寻找适用于字符串或实例中的任何类型的验证关键字whcih。在最新版本的JSON模式中,您可以找到const。
You would add a const key word as follows for your user definition...
您将为您的用户定义添加一个const关键字如下…
...
"user": {
"type": "object",
"properties": {
"type": { "type": "string", "const": "user" },
"age": { "type": "number" }
}
"required": ["age"]
},
...
If const
isn't available to you because you need to use an older version of JSON Schema, you could use enum
which is practically the sam but you woule encase the string "user" inside an array as the value for the enum
key word.
如果const对您不可用,因为您需要使用JSON模式的旧版本,您可以使用enum(实际上是sam),但您可以将数组中的字符串“user”作为enum关键字的值。