json - 为什么 json 模式不验证必需属性中定义的定义
问题描述
我正在尝试创建一个 json 模式,该模式根据对象的类型对其进行验证。它选择正确的定义,但是,它不会验证所选定义中的必需属性。这是我正在尝试的 json 模式:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"literal": {
"type": "object",
"properties": {
"raw": { "type": "string" }
},
"required": ["raw"],
"additionalProperties": false
},
"identifier": {
"type": "object",
"properties": {
"name": { "type": "string" }
},
"required": ["name"],
"additionalProperties": false
}
},
"type": "object",
"oneOf": [
{
"type": "object",
"properties": {
"type": {
"enum": ["Literal"]
},
"content": { "$ref": "#/definitions/literal" }
}
},
{
"type": "object",
"properties": {
"type": {
"enum": ["Identifier"]
},
"content": { "$ref": "#/definitions/identifier" }
}
}
],
"required": ["type"]
};
以下架构是有效的,即使它缺少“原始”属性:
{ "type" : "Literal" }
谢谢
解决方案
JSON Schema 规范中没有关键字content
。
在根模式中断言"type":"object"
后,无需在子模式中再次执行此操作。
为了将对象type
枚举值与关联的扩展定义结合起来,您需要allOf
关键字。
同样在定义中,如果您使用"additionalProperties": false
,则必须列出对象的所有属性(请参阅 参考资料"type": {}
)。对于先前定义/验证的属性,您可以只使用 permissive schema:{}
或true
.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"literal": {
"properties": {
"type": {},
"raw": { "type": "string" }
},
"required": ["raw"],
"additionalProperties": false
},
"identifier": {
"properties": {
"type": {},
"name": { "type": "string" }
},
"required": ["name"],
"additionalProperties": false
}
},
"type": "object",
"oneOf": [
{
"allOf": [
{
"properties": {
"type": {
"enum": ["Literal"]
}
}
},
{"$ref": "#/definitions/literal"}
]
},
{
"allOf": [
{
"properties": {
"type": {
"enum": ["Identifier"]
}
}
},
{"$ref": "#/definitions/identifier" }
]
}
],
"required": ["type"]
}
推荐阅读
- python - 我的 Python 程序说“AttributeError: 'str' object has no attribute 'encode' on line 4”
- php - 使用 DomDocument 将 HTML、CSS 和 JavaScript 从文件中分离出来
- google-api - Google API 访问令牌含义
- php - 以编程方式为 WooCommerce 中的特定可变产品设置最小、最大和步长数量
- docker - nginx 从 foo.bar/app 正确反向加载资产
- javascript - 根据 Acrobat 中其他组合框的结果填充组合框
- php - 为什么 Laravel 网站在直播服务器上运行在两条不同的路径上,路径相同
- python - 基于另一个数据帧 Python 和 Pandas 从数据帧中采样
- reactjs - 为什么我不能在使用 getServerSideProps 或 getInitialProps 的组件的子组件中使用 NextJS 的 useRouter?
- docker - 使用 WORKDIR 命令时 Dockerfile 无法正常工作?