我有一个示例 json:
{
"type": "persons",
"id": 2,
"attributes": {
"first": "something",
"second": "something else"
}
}
我必须为它制作一个架构(使用 JSON API specs 和 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"]
}
问题是:如果“type”的唯一可接受值是“persons”,我应该在模式模式(如上)中使用还是像枚举一样使用
"enum": ["persons"]
我无法从文档中得到任何明确的答案,尽管在规范中的示例中枚举用于单个值。那么你有什么看法呢?
最佳答案
最终,这并不重要。两者都有效,而且都是合理的。也就是说,我见过的最常见的方法是使用 enum
.两者都不是完美的可读性,但我认为 enum
更好的原因有两个。
pattern
需要两行来表达。使用 enum
只需要一个,因为 type
由数组中的值暗示。两行比一行更难阅读,所以如果这行足够表达,我说坚持一。 enum
由于这个原因,可能更容易访问。 关于JSON 模式枚举与单值模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34085443/