JSON schema: referencing a local child schema

2.7k views Asked by At

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

3

There are 3 answers

0
Djiby Thiaw On BEST ANSWER

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

3
cloudfeet On

$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
fge On

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)