Can I set exact value in a JSON Schema?

11,656

Solution 1

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).

Solution 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!

Share:
11,656
Sergei Basharov
Author by

Sergei Basharov

Updated on June 13, 2022

Comments

  • Sergei Basharov
    Sergei Basharov almost 2 years

    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?

  • Jason Desrosiers
    Jason Desrosiers almost 3 years
    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".
  • Jed Godsey
    Jed Godsey almost 3 years
    This is half correct. "const" keyword does not appear to be available in Draft-04 (AWS will not accept it).
  • Jason Desrosiers
    Jason Desrosiers almost 3 years
    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.
  • Nadeem Taj
    Nadeem Taj over 2 years
    I am sure you will perform well next time.
  • Sam
    Sam almost 2 years
    This answer does not add any additional value and seems to be a copy of the currently accepted answer.