2016-05-30 82 views
1

我的代码中有一个特殊的枚举情况和需要来验证它的名单:验证JSON模式为已知值

{ 
    "status": 10 
} 

让我们用有效值这个虚构的名单:

var valid = [10, 20, 23, 27]; 

我怎样才能改变我的JSON模式来验证其中的一个值?

{ 
    type: 'object', 
    required: ['status'], 
    properties: { 
    status: { type: number }, 
    } 
} 

回答

2

你刚才定义status属性作为enum

{ 
    "type" : "object", 
    "required" : ["status"], 
    "properties" : { 
     "status" : { 
      "type" : "number", 
      "enum" : [10, 20, 23, 27] 
     } 
    } 
} 
+0

谢谢!这是我正在寻找的。以下是相关文档:http://json-schema.org/latest/json-schema-validation.html#anchor76 – jocull

0

如果我理解正确的话,我想你会在所有的值必须环路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; 
} 

我简化了一下这个例子,但是你会得到我的漂移。

+1

这是JSON模式的一部分吗?它看起来并不像。 http://json-schema.org/ – jocull

+0

不,我可能误解了这个问题。我提供了一种在Javascript中手动验证JSON的方法。原因是OP包含了Javascript标签。但是现在你发表了你的评论,我怀疑我的答案是OP寻找的。 – David

+0

我猜你不知道JSON模式,这在OP中提到过两次。检查一下 - 这非常有用:http://json-schema.org/ –