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?
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.
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.
Not everyone is comfortable reading regex. enum
might be more accessible for that reason.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With