Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 549
3Gee Avatar asked Dec 04 '15 09:12

3Gee


1 Answers

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.

like image 195
Jason Desrosiers Avatar answered Oct 09 '22 15:10

Jason Desrosiers