5

I'm trying to import the definitions from another json schema using $ref but getting the following error:

can't resolve reference ../base/definitions.schema.json#/definitions/datetime from id #

{
  "$schema": "http://json-schema.org/draft-06/schema#",

  "definitions": {
    "datetime": {
      "type": "string"
    },
    "name": {
      "type": "string"
    },
  }
}

{
  "$schema": "http://json-schema.org/draft-06/schema#",
  "properties": {
    "active": {"type": "boolean"},
    "created_at": { "$ref": "../base/definitions.schema.json#/definitions/datetime" },
    "name": { "$ref": "../base/base/definitions.schema.json#/definitions/name" },
    "updated_at": { "$ref": "../base/definitions.schema.json#/definitions/datetime" }
  },
  "required": ["name"],
  "type": "object"
}

Directory structure:

api
-- base
  -- definitions.schema.json
-- country
  -- country.schema.json

I have tried several combinations by using an absolute path, a file url and several other combinations of the path. Not sure what's going on.

Schema validator: ajv@5.1.1

Sayem
  • 6,079
  • 4
  • 22
  • 26

1 Answers1

8

You need to add schemas using "addSchema" method. $ref is resolved relative to "id" attribute ("$id" in draft-06), ajv doesn't (and can't) use file paths.

EDIT: added $ref section to docs.

esp
  • 7,314
  • 6
  • 49
  • 79
  • 1
    But according to [this](https://spacetelescope.github.io/understanding-json-schema/structuring.html#reuse) I should be able to add a path to `$ref`. See this: `$ref can also be a relative or absolute URI, so if you prefer to include your definitions in separate files, you can also do that.` – Sayem Sep 25 '17 at 06:44
  • 1
    You can use paths, as I wrote they will be resolved using the base URI in id (or $id) attribute. – esp Sep 25 '17 at 07:09
  • I'm a bit confused. Do you mean I have to define the path in the `$id` attribute? What happens if the definitions are in multiple files? Could you please give an example? – Sayem Sep 25 '17 at 07:33
  • You have to define schema URI in $id, then $ref would be seen as path relative to this URI – esp Sep 25 '17 at 07:37
  • You can think that $id is analogous to the location of the schema in the file system (only you should use full URI with the domain name). The spec explicitly says, that validators should not assume that the schema file can be retrieved from this location, it's only used for identification. – esp Sep 25 '17 at 07:43
  • I tried setting the path of the current file as `$id`. But I still can't access a schema relative to the current path. [github gist](https://gist.github.com/afm-sayem/5f2ec980f876128d6d277694888ad9d2) – Sayem Sep 25 '17 at 08:15
  • 2
    Did you use addSchema to add the schema you are trying to access? Does that second schema have $id? Ajv does not do any I/O – esp Sep 25 '17 at 08:17