json - Json 模式验证错误实例为真
问题描述
我有以下架构,我很难理解它为什么不起作用。
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "http://yourdomain.com/schemas/myschema.json",
"title": "Product",
"description": "A product in the catalog",
"type": "object",
"properties": {
"transitions" : {
"description": "defines the transitions to another state",
"type": "object",
"patternProperties": {
"^[0-9]+$": {
"description": "defines a transition for an specific node",
"type":"object",
"properties": {
"next": {
"description": "id of the next transition",
"oneOf": [
{
"type":"string"
},
{
"type": "object",
"patternProperties": {
"^[\\<\\>\\=\\!\\=\\>\\<]\\_[0-9]+$" : {
"type":"string"
}
}
},
{
"type": "object",
"patternProperties": {
"^\\w+( +\\w+)*$" : {
"type":"string"
}
}
}
]
},
"action": {
"description": "id of the transitions action",
"type":"string"
}
}
}
},
"additionalProperties": false
}
},
"required": ["transitions"]
}
例如,正如您在架构中看到的那样,这个特定的 json 实例应该符合next
属性定义之一
"transitions": {
"1": {
"action": "1_input",
"next": {
"test de una novedad": "2"
}
}
}
}
属性模式
{
"type": "object",
"patternProperties": {
"^\\w+( +\\w+)*$" : {
"type":"string"
}
}
}
但是我在在线验证器https://www.jsonschemavalidator.net/中收到了这些错误消息,
Message:
JSON is valid against more than one schema from 'oneOf'. Valid schema indexes: 1, 2.
Schema path:
http://yourdomain.com/schemas/myschema.json#/properties/transitions/patternProperties/^[0-9]+$/properties/next/oneOf
Message:
Invalid type. Expected String but got Object.
Schema path:
http://yourdomain.com/schemas/myschema.json#/properties/transitions/patternProperties/^[0-9]+$/properties/next/oneOf/0/type
我看不出它如何与其中的两个定义相匹配。
有没有人有类似的情况?
提前致谢
解决方案
您的问题在于oneOf
"oneOf": [
{
"type":"string"
},
{
"type": "object",
"patternProperties": {
"^[\\<\\>\\=\\!\\=\\>\\<]\\_[0-9]+$" : {
"type":"string"
}
}
},
{
"type": "object",
"patternProperties": {
"^\\w+( +\\w+)*$" : {
"type":"string"
}
}
}
]
因为"test de una novedad": "2"
第二个和第三个元素都是没有属性限制的对象,所以它都匹配。
要解决此问题,如果您不介意使用两个属性验证对象,可以尝试合并两者:
"oneOf": [
{
"type":"string"
},
{
"type": "object",
"patternProperties": {
"^[\\<\\>\\=\\!\\=\\>\\<]\\_[0-9]+$" : {
"type":"string"
},
"^\\w+( +\\w+)*$" : {
"type":"string"
}
}
}
]
或者你可以添加additionalProperties: false
一个或两个。
"oneOf": [
{
"type":"string"
},
{
"type": "object",
"additionalProperties": false,
"patternProperties": {
"^[\\<\\>\\=\\!\\=\\>\\<]\\_[0-9]+$" : {
"type":"string"
}
}
},
{
"type": "object",
"additionalProperties": false,
"patternProperties": {
"^\\w+( +\\w+)*$" : {
"type":"string"
}
}
}
]
推荐阅读
- java - 解密结果不一致
- java - 在不使用 Log4J 的情况下测试由 Slf4j 创建的日志消息
- python - 我如何通过 Selenium 获得股票代码?
- regex - NGINX 有 2 个需要重写的条件
- python - 运行 python manage.py runserver 返回错误 LookupError: No installed app with label 'admin'
- swift - 集合视图单元格上的重叠阴影
- javascript - 如何在 ES5 中使用 Promise
- java - AudioTrack - IllegalStateException:在未初始化的 AudioTrack 上调用 play()
- javascript - 按标题名称检索 Google 表格列
- android - 如何构建 ViewPager 来滑动大图像?