How to use definitions from external files in JSON Schema?

徘徊边缘 提交于 2020-01-03 18:00:29

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/46388284/how-to-use-definitions-from-external-files-in-json-schema

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!