简体   繁体   English

json 模式验证使用带有 tv4 的 patternProprties

[英]json schema validation using patternProprties with tv4

I have a json like:我有一个 json 像:

{"post": {"someKey": {"anotherKey":"anotherValue"}}}

and where the first key is a valid http method and can be either of - post, get etc all valid http method at runtime.并且第一个键是有效的 http 方法,并且可以是在运行时发布、获取等所有有效的 http 方法。

Here is my schema这是我的架构

var schema = {
    "type": "object",
    "patternProperties": {
        "^[a-z]+$": {
            'properties': {
              "type": "object",
              'properties': {
                'someKey':{
                    'type': 'object',
                    'properties': {
                      'anotherKey': {'type': 'string'},
                    }
                }
            }
        }
      }
   }
}

var valid = { "post": {"mkey":"myvalue"}}; //This is getting passed but I know that is wrong
var invalid = { "1": {"mkey":"myvalue"}}; //This is passed but actually it should fail

console.log(tv4.validateMultiple(invalid, schema));

Can some one help?有人可以帮忙吗?

I figured out:我想通了:

{
    'type': 'object',
    'patternProperties': {
        '^(POST|GET|DELETE|HEAD|PATCH|HEAD|PUT)$': {
            'additionalProperties': false,
            'type': 'object',
            'required': ['someKey'],
            'properties': {
                'someKey': {
                    'type': 'string'
                }
            }
        }
    }
}

Here, things to note: 1.'additionalProperties': false is important for patternProperties 2. As per JSON Schema spec, you cannot have a case insensitive match and hence all are in upper case在这里,需要注意的事情: 1.'additionalProperties': false 对 patternProperties 很重要 2. 根据 JSON Schema 规范,你不能有不区分大小写的匹配,因此所有都是大写的

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

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