简体   繁体   English

NodeJS JSON 架构验证不起作用

[英]NodeJS JSON Schema Validation not working

I'm a complete newbie to JSON Schema Validator, but I think is very powerful.我是 JSON Schema Validator 的完全新手,但我认为它非常强大。 However, I just can't validate one JSON.但是,我无法验证一个 JSON。

This is my 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"]
}

And this is the actual JSON:这是实际的 JSON:

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

So as you can see the "url" property from "original_image" is not there, but the validation returns true!因此,您可以看到“original_image”中的“url”属性不存在,但验证返回true! And, for "new_width" I set the value to null... and again passes validation, so I don't know what I'm doing wrong.而且,对于“new_width”,我将值设置为空...并再次通过验证,所以我不知道我做错了什么。

It seems to be working fine.它似乎工作正常。 The console logs errors correctly.控制台正确记录错误。 This is my index.js这是我的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));

If you put your condition as required:["url","temp_id","scale"] , then, all three properties are required in the payload, but url seems to be missing in your payload.如果您按required:["url","temp_id","scale"]设置条件required:["url","temp_id","scale"] ,则有效负载中需要所有三个属性,但有效负载中似乎缺少url If you want url to be optional, then, dont put it in the required constraint.如果你希望url是可选的,那么,不要把它放在必需的约束中。 The validator also gives back an error message.It returns missing parameters/properties if that is the case.验证器还会返回一条错误消息。如果是这种情况,它会返回缺少的参数/属性。

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

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