JSON schema $ref does not work for relative path

ahri picture ahri · Aug 5, 2014 · Viewed 11k times · Source

I have 3 schemas:

child schema:

{
    "title": "child_schema",
    "type": "object",
    "properties": {
        "wyx":{
            "type": "number"
        }
     },
    "additionalProperties": false,
    "required": ["wyx"]
}

parent schema:

{
    "title": "parent",
    "type": "object",
    "properties": {
        "x": {
            "type": "number"
        },
        "y": {
            "type": "number"
        },
        "child": {
            "$ref": "file:child.json"
        }
    }
}

grandpa schema:

{
    "type": "object",
    "title": "grandpa",
    "properties": {
        "reason": {
            "$ref": "file:parent.json"
        }
    },
    "additionalProperties": false
}

As you can see, gradpa has a ref to parent and parent has a ref to child. All these 3 files are inside the same folder. When I use python validator to validate grandpa schema, I will keep on getting an error called RefResolutionError.

HOWEVER, if I do not have grandpa and I just use parent schema and child schema, everything worked!! So the issue is I cannot have a ref pointing to a ref(2 levels). But I can have a ref pointing to a schema(just 1 level.)

I wonder why

Answer

Alex-Bogdanov picture Alex-Bogdanov · Oct 14, 2015

Your references are incorrect. If the referenced schemes are in the same folder, use simple relative path references like:

"child": {"$ref": "child.json"},
"reason": {"$ref": "parent.json"}

If you're using jsonschema for validation, don't forget to set a reference resolver in order to resolve the paths to referenced schemas:

import os
from jsonschema import validate, RefResolver

instance = {}
schema = grandpa

# this is a directory name (root) where the 'grandpa' is located
schema_path = 'file:///{0}/'.format(
      os.path.dirname(get_file_path(grandpa)).replace("\\", "/"))
resolver = RefResolver(schema_path, schema)
validate(instance, schema, resolver=resolver)