3Ge*_*Gee 6 enums json jsonschema json-api
我有一个示例json:
{
"type": "persons",
"id": 2,
"attributes": {
"first": "something",
"second": "something else"
}
}
Run Code Online (Sandbox Code Playgroud)
我必须为它制作一个模式(使用JSON API规范和JSON模式文档):
{
"$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"]
}
Run Code Online (Sandbox Code Playgroud)
问题是:如果"类型"唯一可接受的值是"人",我应该使用模式模式(如上所述)还是枚举类似
"enum": ["persons"]
Run Code Online (Sandbox Code Playgroud)
我无法从文档中得到任何明确的答案,尽管在规范枚举中的示例用于单个值.你有什么看法?
最终,它并不重要.两者都有效,两者都合理.也就是说,我见过的最常见的方法是使用enum.两者都不是完美的可读性,但我认为enum有两个原因更好.
使用pattern需要两行来表达.使用enum只需要一个因为type数组中的值所暗示的.两条线比一条线更难读,所以如果那条线足够表达,我说坚持一条线.
不是每个人都习惯阅读正则表达式. enum因此可能更容易接近.
自草案6起,有一个const针对此用例的新关键字。
"type": {
"type": "string",
"const": "persons"
},
Run Code Online (Sandbox Code Playgroud)
http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.1.3
| 归档时间: |
|
| 查看次数: |
3301 次 |
| 最近记录: |