如何pipe理多个JSON模式文件?

我试图使用commonjs-utils中的node.js + json-schema.js来validation我的JSON API。 只是单一的validation很容易,但找不到正确的方式来pipe理多个模式文件以引用对方。

假设我有两个模型和两个API。

// book { "type": "object", "properties": { "title": { "type": "string" }, "author": { "type": "string" } } } // author { "type": "object", "properties": { "first_name": { "type": "string" }, "last_name": { "type": "string" } } } // authors API { "type": "array", "items": { "$ref": "author" } } // books API: list of books written by same author { "type": "object", "properties": { "author": { "$ref": "author" } "books": { "type": "array", "items": { "$ref": "book" } } } } 

每个模式应该被分割成单独的文件并在线? 或者我可以合并成下面的单个模式文件吗? 如果可能,我怎样才能引用本地模式?

 // single schema file { "book": { ... }, "author": { ... }, "authors": { ... }, "books": { ... } } 

在JSON模式中,您可以为每个文件放置一个模式,然后使用它们的URL(存储它们的位置)或具有id标记的大模式访问它们。

这是一个大文件:

 { "id": "#root", "properties": { "author": { "id": "#author", "properties": { "first_name": { "type": "string" }, "last_name": { "type": "string" } }, "type": "object" }, // author "author_api": { "id": "#author_api", "items": { "$ref": "author" }, "type": "array" }, // authors API "book": { "id": "#book", "properties": { "author": { "type": "string" }, "title": { "type": "string" } }, "type": "object" }, // books API: list of books written by same author "books_api": { "id": "#books_api", "properties": { "author": { "$ref": "author" }, "books": { "items": { "$ref": "book" }, "type": "array" } }, "type": "object" } } } 

然后你可以引用你的validation器到其中一个子模式(用id定义)。

从你的模式之外,这个:

 { "$ref": "url://to/your/schema#root/properties/book" } 

相当于这个:

 { "$ref": "url://to/your/schema#book" } 

…从内部相当于这个:

 { "$ref": "#root/properties/book" } 

或这(仍然从内部):

 { "$ref": "#book" } 

有关更多信息,请参阅我的答案 。