5

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?

ra9r
  • 4,528
  • 4
  • 42
  • 52

1 Answers1

3

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).

esp
  • 7,314
  • 6
  • 49
  • 79
  • That did fix the issue but could you explain why `#/definitions/phone` worked and the `#definitions/phone` does not? All the documentation from the developer would imply otherwise. Thanks! – ra9r Oct 28 '16 at 19:09
  • What documentation you refer to? I am the developer btw :) That's by the spec, the reference within the current schema is # followed by JSON pointer, JSON pointer starts from "/" – esp Oct 28 '16 at 19:11
  • Great library, thank you for contributing it for the rest of us. As for your question, I could have sworn that I saw that in examples on the json-schema.org website but for the life of me I can't find any examples as proof. So I must be going blind or insane. Thank you for the prompt response. – ra9r Oct 29 '16 at 15:35