【问题标题】:json schema validation using patternProprties with tv4使用带有 tv4 的 patternProprties 进行 json 模式验证
【发布时间】:2019-09-23 14:08:09
【问题描述】:

我有一个像这样的json:

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

其中第一个键是有效的 http 方法,可以是 - post、get 等在运行时所有有效的 http 方法。

这是我的架构

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));

有人可以帮忙吗?

【问题讨论】:

    标签: node.js json support-v4 tv4


    【解决方案1】:

    我想通了:

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

    这里,注意事项: 1.'additionalProperties': false 对 patternProperties 很重要 2. 根据 JSON Schema 规范,你不能有一个不区分大小写的匹配,因此所有的都是大写的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-21
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 2011-02-15
      相关资源
      最近更新 更多