JSON schema: referencing a local child schema

有些话、适合烂在心里 提交于 2019-12-08 08:17:39

问题


I want to reference a child schema in a parent json schema. Here is the child schema named child.json

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

and here is the parent schema named parent.json and all the two files are in the same folder. I want to refer to the child schema and i do like this:

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

I've an error saying that the file child.json is not found. I've tested lot of tings but anyone is working.
Thanks for your help


回答1:


I've found a solution for my problem. Here is the solution
The context is that we always have two schemas: the parent and the child. The parent have to include the child schema in one of his properties like this par exemple:

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

And in the child schema at the beginning of him, you have to put an id on it like this

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

Now for the validation with jaySchema you will do like this

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
});

And it's all. :-D
This is my solution but it's not the best and i hope that it will help. Thanks to all for your answers




回答2:


$ref values can be URI References - they don't need to be absolute URIs. So here, you should just be able to use:

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

and it should resolve appropriately.




回答3:


If your parent and child schemas are in the classpath and in the same place then the best thing to do is to use the custom resource URI scheme to load it with an absolute URI:

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

Then you can reference your child schema using { "$ref": "child.json" } (since JSON References are resolved relatively to the current schema's URI)



来源:https://stackoverflow.com/questions/26920482/json-schema-referencing-a-local-child-schema

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!