如何制作jsonschema,以便验证数组中的所有对象? [英] How do I make a jsonschema so that it validates all objects in array?

查看:68
本文介绍了如何制作jsonschema,以便验证数组中的所有对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用json-schema验证JSON输入,但无法正常工作.

I'm trying to validate a JSON input using json-schema but it does not work like I need it to.

我有以下输入JSON(部分):

I have the following input JSON (part of it):

[
  {
    "admin_state": "disabled"
  },
  {
    "state": "disabled"
  }
]

以及以下json模式(也是其中的一部分):

And the following json-schema (part of it as well):

{
  "type": "array",
  "items": [
    {
      "type": "object",
      "properties": {
        "admin_state": {
          "type": "string",
          "default": "enabled",
          "enum": [
            "disabled",
            "enabled"
          ]
        }
      },
      "additionalProperties": false
    }
  ],
  "minItems": 1
}

我希望由于"state"属性不被允许而导致验证失败(由于"additionalProperties":false 选项)

I want the validation to fail because of the "state" property that should not be allowed (thanks to the "additionalProperties": false option)

但是,我可以在数组的第二项中添加/更改任何内容,因此验证总是成功的.当我在第一项中进行任何更改时,验证都会失败(按预期方式).

However, I can add/change anything in the second item in the array, validation is always successful. When I change anything in the first item, validation fails (as expected).

我想念什么?

感谢您的帮助!

推荐答案

JSON模式草稿7个状态...

JSON Schema draft 7 states...

如果"items"是一个架构,如果阵列针对该架构成功验证.

If "items" is a schema, validation succeeds if all elements in the array successfully validate against that schema.

如果"items"是一个模式数组,如果每个元素都通过验证,实例的实例将针对同一位置的架构进行验证,如果任何.

If "items" is an array of schemas, validation succeeds if each element of the instance validates against the schema at the same position, if any.

在您的架构中, items 是一个数组,这意味着您仅将该数组中的subschem应用于实例数组的第一个元素.只需从 items 中删除方括号,您的子模式将适用于实例中的所有项.

In your schema, items is an array, which means you were only applying the subschem in that array to the first element of your instance's array. Simply remove the square braces from items, and your subschema will be applicabale to ALL items in the instance.

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "admin_state": {
        "type": "string",
        "default": "enabled",
        "enum": [
          "disabled",
          "enabled"
        ]
      }
    },
    "additionalProperties": false
  },
  "minItems": 1
}

这篇关于如何制作jsonschema,以便验证数组中的所有对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆