2016-10-04 60 views
1

我是JSON Schema Validator的完全新手,但我认为它非常强大。但是,我只是无法验证一个JSON。NodeJS 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 ...并再次通过验证,因此我不知道我在做什么错误。

回答

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

我正在使用json-schema,破折号,但没有它的jsonschema看起来很好。所以我想我会切换到“jsonschema”包,工作! –

0

如果你把你的病情为required:["url","temp_id","scale"],那么,所有的三个属性都需要在有效载荷,但url似乎在你的有效载荷将丢失。 如果你想url是可选的,那么不要把它放在必需的约束中。 验证器还返回错误消息。如果是这种情况,它将返回缺少的参数/属性。

+0

不,这就是问题所在,我不希望url是可选的。问题是,即使在需要,它不返回和错误。它应该是因为不存在,但它返回true,所以验证是错误的。 –