【问题标题】:Why does json schema validate json with missing properties为什么 json 模式会验证缺少属性的 json
【发布时间】:2023-03-20 05:58:01
【问题描述】:

我正在使用这个 json 模式验证器:https://www.jsonschemavalidator.net/ 来验证一些 json。令我惊讶的是,即使 json 中缺少属性,它也会验证架构。

架构

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "properties": {
      "test": {
        "type": "array"
      }
    }
}

应该验证

{
    "test": []
}

不应该验证(但验证!)

{}

为什么这被认为是有效的,我如何验证 json 以便属性 test 必须是 json 的一部分?

【问题讨论】:

  • 您必须将“additionalProperties”设置为false
  • 谢谢@Pedro,看来我的问题还不够清楚。您的评论帮助我找到了使用required的解决方案。

标签: json validation jsonschema


【解决方案1】:

有一个required 属性可以做到。默认情况下,验证似乎对所有属性使用required: false

这会验证并强制属性存在:

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "properties": {
      "test": {
        "type": "array"
      }
    },
    "required": ["test"]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多