json - 如果数组中没有项目时不需要数组,如何指定 JSON Schema?

标签 json jsonschema

假设我有一些像这样的 json 数据:

{
    "quantity": 3,
    "modifiers": [{}]
}

如果无意将对象添加到修饰符中,我不希望存在修饰符

如果没有修饰符,这应该是正确的方法:

{
    "quantity": 3,
}

并且使用修饰符应该是正确的:

{
    "quantity": 3,
    "modifiers": [{
        "testing": "some data here"
    }]
}

我将如何构建 JSON 架构来验证上面的示例是否正确?

编辑: 上述示例的 JSON 架构示例:

{
    "type": "object",
    "properties": {
        "quantity": {
            "type": "integer",
            "minimum": 1
        },
        "modifiers": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "testing": {
                        "type": "string"
                    }
                }
            },
            "minItems": 1
        }
    },
    "required": [
        "quantity"
    ]
}

最佳答案

(仅限草案 7)要不允许允许数组为空(如果存在),请执行以下操作:

  "if": {
    "required": [
      "modifiers"
    ]
  },
  "then": {
    "properties": {
      "modifiers": {
        "minItems": 1
      }
    }
  }

这将确保这是无效的:

{
    "quantity" : 1,
      "modifiers":[]
}

但请注意,以下 json 是有效的:

{
    "quantity" : 1,
      "modifiers":[{}]
}

如果您不希望这样,请确保包含适当的必填 字段。这就是基于上面给定示例/架构的最终架构的样子:

{
  "type": "object",
  "properties": {
    "quantity": {
      "type": "integer",
      "minimum": 1
    },
    "modifiers": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "testing": {
            "type": "string"
          }
        },
        "required": [
          "testing"
        ]
      },
      "minItems": 1
    }
  },
  "required": [
    "quantity"
  ],
  "if": {
    "required": [
      "modifiers"
    ]
  },
  "then": {
    "properties": {
      "modifiers": {
        "minItems": 1
      }
    }
  }
}

现在,这也是无效的:

{
    "quantity" : 1,
      "modifiers":[{}]
}

这是有效的:

{
    "quantity" : 1,
      "modifiers":[{"testing":"343"}]
}

关于json - 如果数组中没有项目时不需要数组,如何指定 JSON Schema?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49529974/

相关文章:

json - 递归 JSON 模式

Javascript 从 Json 文件获取图像和按钮下一个和上一个功能

javascript - 将 JSON 从 Javascript 转换为 PHP

javascript - JSONSchema 和验证子对象属性

javascript - 为什么 JSON API 规范建议使用连字符/减号来分隔成员名称中的单词?

python - 如何使用 pydantic 生成严格的 json 模式?

php - 是否需要验证或转义 jsonp 回调字符串

PHP 5.1.6 上的 PHP 变量到 JSON

javascript - Bing 搜索 API 似乎忽略了 $top 值

javascript - 元组数组的 JSON 模式