30

I use JSON Schema to validate app objects against some schema for testing.

I see that I can set minimum and maximum values for a property:

"responseCode": {
        "type": "integer",
        "minimum": 100,
        "maximum": 500
    }

But I couldn't find if I can set an exact required value, like "value":123.

Is it possible to set it to exactly what I need to validate for?

Sergei Basharov
  • 51,276
  • 73
  • 200
  • 335

3 Answers3

60

You can:

{ "enum": [123] }

or

{ "const": 123 }

const is now part of draft-06 of JSON schema specification (it is supported by Ajv and some other validators).

Will S
  • 744
  • 8
  • 17
esp
  • 7,314
  • 6
  • 49
  • 79
2

In case anybody was wondering how to specify a string value rather than a number, especially in AWS API Gateway, which uses JSON Schema Draft-04, You can use regular expressions:

{
    "type": "string",
    "pattern": "MyStringOrOtherRegex"
}

https://datatracker.ietf.org/doc/html/draft-fge-json-schema-validation-00#section-3.3

Jed Godsey
  • 77
  • 2
  • 8
  • 1
    This isn't necessary. `enum` and `const` work for strings (and any other type for that matter). Also, if you do this, make sure to anchor your regex with `^` and `$`. Otherwise something like `"pattern": "a"` will match "cat". – Jason Desrosiers Jun 16 '21 at 18:56
  • This is half correct. "const" keyword does not appear to be available in Draft-04 (AWS will not accept it). – Jed Godsey Jun 17 '21 at 19:31
  • I just meant that `const` works with strings. I didn't mean to imply that `const` worked in draft-04. But, the way I wrote it was certainly confusing. Thank you for pointing that out. – Jason Desrosiers Jun 17 '21 at 22:35
-2

Already mentioned but the 2 options I know are:

{ "enum": [123] }

and

{ "const": 123 }

My source was: https://json-schema.org/understanding-json-schema/reference/generic.html

Keep up the good work!