【问题标题】:NodeJS JSON Schema Validation not workingNodeJS JSON模式验证不起作用
【发布时间】:2016-10-04 03:10:30
【问题描述】:

我是 JSON Schema Validator 的新手,但我认为它非常强大。但是,我无法验证一个 JSON。

这是我的架构

 {
  title: "Example  Schema",
  type: "object",
  properties: {
    original_image:{
      type: "object",
      properties: {
        temp_id: {type: "string"},
        url: {type: "string"},
        scale:{
          type: "object",
          properties:{
            new_width: {type: "number"},
            new_height: {type: "number"}
          },
          required:["new_width","new_height"]
        }
      },
      required:["url","temp_id","scale"]
    }
  },
  required:["image"]
}

这是实际的 JSON:

{
  "original_image": {
    "temp_id": "this is my id",
    "scale": {
      "new_width": null,
      "new_height": 329
    }
  }
}

因此,您可以看到“original_image”中的“url”属性不存在,但验证返回 true!而且,对于“new_width”,我将值设置为 null... 并再次通过验证,所以我不知道自己做错了什么。

【问题讨论】:

    标签: node.js jsonschema json-schema-validator


    【解决方案1】:

    它似乎工作正常。控制台正确记录错误。这是我的index.js

    var Validator = require('jsonschema').Validator;
    var v = new Validator();
    var instance = {
      "original_image": {
        "temp_id": "this is my id",
        "scale": {
          "new_width": null,
          "new_height": 329
        }
      }
    };
    var schema = {
      title: "Example  Schema",
      type: "object",
      properties: {
        original_image:{
          type: "object",
          properties: {
            temp_id: {type: "string"},
            url: {type: "string"},
            scale:{
              type: "object",
              properties:{
                new_width: {type: "number"},
                new_height: {type: "number"}
              },
              required:["new_width","new_height"]
            }
          },
          required:["url","temp_id","scale"]
        }
      },
      required:["image"]
    };
    console.log(v.validate(instance, schema));
    

    【讨论】:

    • 我使用的是带有破折号的 json-schema,但没有它的 jsonschema 似乎运行良好。所以我想我会切换到“jsonschema”包,这行得通!
    【解决方案2】:

    如果您将条件设置为 required:["url","temp_id","scale"] ,那么负载中需要所有三个属性,但您的负载中似乎缺少 url 。 如果您希望 url 是可选的,那么,不要将它放在所需的约束中。 验证器还会返回一条错误消息。如果是这种情况,它会返回缺少的参数/属性。

    【讨论】:

    • 不,这正是问题所在,我不希望 url 是可选的。问题是,即使是必需的,它也不会返回和错误。应该是因为不存在,但是它返回true,所以验证是错误的。
    猜你喜欢
    • 2018-09-16
    • 2016-01-30
    • 1970-01-01
    • 2014-01-10
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    相关资源
    最近更新 更多