3Gee
3Gee

Reputation: 1164

JSON schema enum vs pattern for single value

I have an sample json:

{
    "type": "persons",
    "id": 2,
    "attributes": {
        "first": "something",
        "second": "something else"
    }
}

And I have to make a schema for it (using JSON API specs and JSON schema docs):

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "properties": {
        "type": {
            "type": "string",
            "pattern": "^persons$"
        },
        "id": {
            "type": "integer"
        },
        "attributes": {
            "type": "object",
            "properties": {...}
        }
    },
    "required": ["type", "id", "attributes"]
}

And the question is: if the only acceptable value for "type" is "persons", should I use in schema pattern (like above) or enum like

"enum": ["persons"]

I couldn't get any clear answer from documentation, although in examples in specs enums are used for single values. So what's your opinion?

Upvotes: 7

Views: 9299

Answers (2)

schettino72
schettino72

Reputation: 3170

Since draft-6 there is a new keyword called const for this use-case.

"type": {
        "type": "string",
        "const": "persons"
},

http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.1.3

Upvotes: 12

Jason Desrosiers
Jason Desrosiers

Reputation: 24409

Ultimately, it doesn't really matter. Both will work and both are reasonable. That said, the most common approach I've seen is to use enum. Neither are perfect for readability, but I think enum is better for two reasons.

  1. Using pattern requires two lines to express. Using enum requires only one because type is implied by the value in the array. Two lines are harder to read than one, so if that line is expressive enough, I say stick with one.

  2. Not everyone is comfortable reading regex. enum might be more accessible for that reason.

Upvotes: 12

Related Questions