2016-10-04 82 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,所以驗證是錯誤的。 –