简体   繁体   English

如果可选属性无效,则JSON Schema引发验证错误

[英]JSON Schema throw validation error if invalid optional attribute

I have a json schema as shown below which has three properties height,weight and volume which are optional. 我有一个如下所示的json模式,它具有三个属性height,weight和volume,它们是可选的。 But I want to do following additional check here: 但我想在这里进行以下其他检查:

  1. If any other attributes apart from height,weight and volume is passed then it should throw an error 如果传递了除高度,重量和体积之外的任何其他属性,则应引发错误

Not sure how to achieve this since these are optional attributes. 由于这些是可选属性,因此不确定如何实现。

  {
            "$schema": "http://json-schema.org/draft-04/schema#",
            "type": "object",
            "properties": {
              "options": {
                "type": "object",
                "properties": {
                  "height": {
                    "type": "number"
                  },
                  "weight": {
                    "type": "number"
                  },
                  "volume": {
                    "type": "number"
                  }
               }
             }
            }
          }

What you're looking for is the additionalProperties key. 您正在寻找的是additionalProperties键。 From JsonSchema docs 来自JsonSchema文档

The additionalProperties keyword is used to control the handling of extra stuff, that is, properties whose names are not listed in the properties keyword. AdditionalProperties关键字用于控制其他内容的处理,即名称未在properties关键字中列出的属性。 By default any additional properties are allowed. 默认情况下,允许任何其他属性。

So, this yould become: 因此,此友情变为:

 {
            "$schema": "http://json-schema.org/draft-04/schema#",
            "type": "object",
            "properties": {
              "options": {
                "type": "object",
                "properties": {
                  "height": {
                    "type": "number"
                  },
                  "weight": {
                    "type": "number"
                  },
                  "volume": {
                    "type": "number"
                  }
               },
               "additionalProperties": false
             }
            }
          }

From my understanding, this is supported since draft 00 , so it should be ok with draft 4 , but just for you to know, the 8th version is here. 据我了解,自draft 00就支持此功能,因此draft 4应该可以,但仅供您了解,此处是第8版。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM