验证已知值列表的 JSON 模式
Validate JSON Schema for list of known values
我的代码中有一个特殊的枚举案例,需要对其进行验证:
{
"status": 10
}
让我们使用这个虚构的有效值列表:
var valid = [10, 20, 23, 27];
如何更改我的 JSON 架构以验证这些值之一?
{
type: 'object',
required: ['status'],
properties: {
status: { type: number },
}
}
您只需将 status
属性 定义为 enum
:
{
"type" : "object",
"required" : ["status"],
"properties" : {
"status" : {
"type" : "number",
"enum" : [10, 20, 23, 27]
}
}
}
如果我理解正确的话,我想你必须遍历所有值,因为 Javascript 没有像枚举这样的东西。
var validValues = [ 10, 20, 23, 27 ];
var statusType = json.properties.status.type;
/* This function call will return a boolean that tells you wether the value in your json is valid or not.*/
isValid( statusType );
function isValid( statusType )
{
for( var i = 0; i < validValues.length; i++ )
if( statusType === validValues[i] )
return true;
return false;
}
我稍微简化了示例,但您会明白我的意思。
我的代码中有一个特殊的枚举案例,需要对其进行验证:
{
"status": 10
}
让我们使用这个虚构的有效值列表:
var valid = [10, 20, 23, 27];
如何更改我的 JSON 架构以验证这些值之一?
{
type: 'object',
required: ['status'],
properties: {
status: { type: number },
}
}
您只需将 status
属性 定义为 enum
:
{
"type" : "object",
"required" : ["status"],
"properties" : {
"status" : {
"type" : "number",
"enum" : [10, 20, 23, 27]
}
}
}
如果我理解正确的话,我想你必须遍历所有值,因为 Javascript 没有像枚举这样的东西。
var validValues = [ 10, 20, 23, 27 ];
var statusType = json.properties.status.type;
/* This function call will return a boolean that tells you wether the value in your json is valid or not.*/
isValid( statusType );
function isValid( statusType )
{
for( var i = 0; i < validValues.length; i++ )
if( statusType === validValues[i] )
return true;
return false;
}
我稍微简化了示例,但您会明白我的意思。