Search code examples
node.jsjsonschemaajv

Why is Ajv unable to resolve reference during compile?


The following is an example of the JSON schema that I am trying to compile and use for validation. To accomplish this I am using the 'ajv' npm module.

Here is the code that I am running ...

var ajv = require('ajv')();

var contactSchema = {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "Contact",
    "type": "object",
    "additionalProperties": false,
    "properties": {
        "work": { "$ref": "#definitions/phone" },
        "home": { "$ref": "#definitions/phone" },
    },
    "definitions": {
        "phone": {
            "type": "object",
            "required": ["number"],
            "properties": {
                "number": { "type": "string" },
                "extension": { "type": "string" }
            }
        }
    }
};

var validator = ajv.compile(contactSchema);

When I run this code, I am getting the following exception ..

Error: can't resolve reference #definitions/phone from id #

Has anyone else run into this kind of issue? Any idea what I might be doing wrong?


Solution

  • Your reference is incorrect (although it's valid), it should be #/definitions/phone

    Alternatively, to make it work you can add "id": "#definitions/phone" inside phone schema, but it is more common to use "id": "#phone" (and update $refs too).