如何使用 JSON 模式验证键的字符串值?
How can I validate the string value of a key using JSON Schema?
我发现很难理解如何使用不同的验证集来验证不同类型的响应。我只是放了一个示例代码,然后尝试解释它可能有意义。
示例数据集:
responses: [
{ type: 'user', age: 5 }
{ type: 'admi', auth: {...} }
]
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" }
]
}
}
如何根据类型(不是 string, number
,而是 'user', 'admi'
)验证这些?
您将寻找适用于字符串或实例中任何类型的验证关键字。在最新版本的 JSON Schema 中,您可以找到 const
.
您可以为您的用户定义添加一个 const 关键字...
...
"user": {
"type": "object",
"properties": {
"type": { "type": "string", "const": "user" },
"age": { "type": "number" }
}
"required": ["age"]
},
...
如果 const
对您不可用,因为您需要使用旧版本的 JSON Schema,您可以使用 enum
,这实际上是 sam,但您需要 encase数组中的字符串 "user" 作为 enum
关键字的值。
我发现很难理解如何使用不同的验证集来验证不同类型的响应。我只是放了一个示例代码,然后尝试解释它可能有意义。
示例数据集:
responses: [
{ type: 'user', age: 5 }
{ type: 'admi', auth: {...} }
]
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" }
]
}
}
如何根据类型(不是 string, number
,而是 'user', 'admi'
)验证这些?
您将寻找适用于字符串或实例中任何类型的验证关键字。在最新版本的 JSON Schema 中,您可以找到 const
.
您可以为您的用户定义添加一个 const 关键字...
...
"user": {
"type": "object",
"properties": {
"type": { "type": "string", "const": "user" },
"age": { "type": "number" }
}
"required": ["age"]
},
...
如果 const
对您不可用,因为您需要使用旧版本的 JSON Schema,您可以使用 enum
,这实际上是 sam,但您需要 encase数组中的字符串 "user" 作为 enum
关键字的值。