JSON模式:引用本地子模式

时间:2014-11-13 23:35:30

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

我想在父json模式中引用子模式。这是名为child.json的子模式

{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Child",
"description": "Child schema",
"type": "object",
"properties": {
    "name": {"type": "string"},
    "age": {"type": "integer"}
}}

这里是名为parent.json的父模式,所有这两个文件都在同一个文件夹中。我想引用子模式,我喜欢这样:

{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Parent",
"description": "Parent schema",
"type": "object",
"properties": {
"allOf": [
    {
        "$ref": "file://child.json"
    }
],
"adresse": {"type": "string"}
}}

我发现错误,说找不到文件child.json。我测试过很多铃声,但是有人在工作。
谢谢你的帮助

3 个答案:

答案 0 :(得分:2)

我找到了解决问题的方法。这是解决方案
上下文是我们总是有两个模式:父模式和子模式。父母必须在他的一个属性中包含子模式,例如这个例子:

"myChild": {
      "$ref": "child" //referencing to child schema
}

在他开头的子模式中,你必须像这样把放在它上面

{
    "id": "child", //important thing not to forget
    "$schema": "http://json-schema.org/draft-04/schema#"
    //other codes goes here
}

现在使用jaySchema验证你会这样做

var js = new JaySchema();
var childSchema = require('./child.json');
var parentSchema = require('./parent.json');

//other codes goes here
js.register(childSchema); //important thing not to forget
js.validate(req.body, schema, function(err) {
    if (err) //your codes for err
});

就是这样。 :-D
这是我的解决方案,但它不是最好的,我希望它会有所帮助。感谢所有人的回答

答案 1 :(得分:1)

$ref值可以是URI引用 - 它们不需要是绝对URI。所以在这里,你应该能够使用:

{"$ref": "child.json"}

它应该妥善解决。

答案 2 :(得分:0)

如果您的父模式和子模式位于类路径中且位于相同位置,那么最好的办法是使用自定义resource URI方案加载绝对URI:

final JsonSchema schema = factory.getJsonSchema("resource:/path/to/parent.json");

然后,您可以使用{ "$ref": "child.json" }引用您的子模式(因为JSON引用是相对于当前模式的URI解析的)