jsonschema multiple values for string property

Jeff U. picture Jeff U. · Oct 23, 2014 · Viewed 19.1k times · Source

I have a json schema which describes a fairly complex API querying syntax. A few of the properties are pattern matched but also need to accept other values (i.e. other explicit strings) other than just the pattern. I can't seem to find anywhere in the multitude of json schema sites any examples of this.

An example:

{
    "type": "object",
    "properties": {
        "$gte": {
            "type": "string",
            "pattern": "<some-pattern>"
        }
    }
}

What i'd like to be able to do in the example above is specify that $gte can be any of a certain set of constrained values. For example, this specific implementation requires that "$gte"'s values be constrained to one of the following:

  1. A specific date format
  2. A token {token} which gets replaced with a special value on the server-side

I've seen the oneOf property used in this situation but only with the format property so I'm assuming that this is possible, just not sure of the syntax of how to implement it, for instance it could be something like this:

{
    "type": "object",
    "properties": {
        "$gte": {
            "type": "string",
            "oneOf": [
                {"pattern": "<some-pattern>"},
                "{token}",
                "{another_token}"
            ]
        }
    }
}

Any clarity on how to accomplish this would be greatly appreciated as I'm not having much luck with the specification Draft 4 for json schema or in finding any examples.

Answer

cloudfeet picture cloudfeet · Oct 23, 2014

If you want data to be one of a fixed set of exact values, you can use enum:

{
    "type": "string",
    "enum": ["stop", "go"]
}

So, to fit this in your example, try:

{
    "type": "object",
    "properties": {
        "$gte": {
            "type": "string",
            "oneOf": [
                {"pattern": "<some-pattern>"},
                {"enum": ["TOKEN", "ANOTHER_TOKEN"]}
            ]
        }
    }
}