8

I have a special enum case in my code and need to validate against it:

{
  "status": 10
}

Let's use this imaginary list of valid values:

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

How can I alter my JSON Schema to validate one of these values?

{
  type: 'object',
  required: ['status'],
  properties: {
    status: { type: number },
  }
}
jocull
  • 20,008
  • 22
  • 105
  • 149

2 Answers2

13

You just define the status property as an enum:

{
    "type" : "object",
    "required" : ["status"],
    "properties" : {
        "status" : {
            "type" : "number",
            "enum" : [10, 20, 23, 27]
        }
    }
}
jruizaranguren
  • 12,679
  • 7
  • 55
  • 73
  • Thank you! This is what I was looking for. Here is the relevant documentation: http://json-schema.org/latest/json-schema-validation.html#anchor76 – jocull Jun 27 '16 at 13:37
0

If I understand you correctly, I think you'll have to loop through all the values as Javascript does not have a thing like enums.

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;
}

I have simplified the example a bit, but you'll get my drift.

David
  • 1,227
  • 12
  • 23
  • No it is not, I may have misunderstood the question. I have provided a way to validate the JSON by hand in Javascript. The reason for this is that OP has included the Javascript tag. But now you posted your comment, I doubt my answer was the one that OP was looking for. – David Jun 27 '16 at 13:42
  • 1
    I guess you don't know about JSON Schema, which is mentioned twice in the OP. Check it out—it's quite useful: http://json-schema.org/ – Michael Scheper Sep 29 '17 at 14:11