1

我想在父 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。我已经测试了很多东西,但任何人都在工作。
谢谢你的帮助

4

3 回答 3

2

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

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

而在他开头的子模式中,你必须像这样在上面放一个id

{
    "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
这是我的解决方案,但不是最好的,我希望它会有所帮助。感谢大家的回答

于 2014-11-19T18:50:11.000 回答
1

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

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

它应该适当地解决。

于 2014-11-14T13:08:53.233 回答
0

如果您的父模式和子模式在类路径中并且在同一个位置,那么最好的办法是使用自定义resourceURI 方案以绝对 URI 加载它:

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

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

于 2014-11-17T17:48:51.867 回答