如何正确引用其他JSON架构文档($ ref)

时间:2015-10-29 17:05:05

标签: json jsonschema

我已经阅读了有关JSON Schema和JSON指针的RFC,但我仍然在努力了解如何正确引用其他文档。

假设我有以下文件(在磁盘上):

/foo/bar/schema/base.json
/foo/bar/schema/model/model.json

base.json像这样:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "/schema/base",
  "title": "Base Response",
  "description": "Schema descriptions of common properties of a response",
  "type": [ "object" ],

  "definitions": {
    "data": {
      "descrpition": "The response data is encapsulated within here",
      "example": "true",
      "type": [ "object", "array", "boolean", "null" ]
    }
  },

  "properties": {
    "data": { "$ref" : "#/definitions/data" }
  }
}

model.json文件是这样的:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "/schema/model/model",
  "type": "object",

  "$ref": "/schema/base.json"
}

model.json中的$ ref值是我要问的。我对标准的理解是在文档的id和$ ref之间,我们应该能够找到该文档。

或者,我想知道是否像:

"$ref": "../../base.json"

会工作吗?

但这些解决方案似乎都不能使用我尝试过的Python或PHP库。我不确定我哪里出错了?

1 个答案:

答案 0 :(得分:6)

First of all, different libraries tackle $ref resolution in different ways, so you will need to follow their specific documentation to figure out the exact details. But below is some general information about $ref resolution that you might find helpful.

Think of your schema document as webpage you are viewing in a browser. The id represents the URL in your browser's URL bar. It must be a full absolute normalized URL, just like in your browser.

{
  "id": "file:///path/to/project/foo/bar/schema/model/model.json"
}

Think of $ref like a link in the webpage you are viewing in the browser. In can be absolute or relative, just like in your browser. A relative $ref will resolve following the same rules as a link on a webpage. For example, I would expect all $refs in the following JSON to resolve to the same value. (Note: it is not valid to use more than one $ref. This is just for illustration.)

{
  "id": "file:///path/to/project/foo/bar/schema/model/model.json",
  "$ref": "file:///path/to/project/foo/bar/schema/base.json",
  "$ref": "/path/to/project/foo/bar/schema/base.json",
  "$ref": "../model.json"
}

If id is not present, the URI used to retrieve the schema should be assumed to be the id. In this case file:///path/to/project/foo/bar/schema/model/model.json.

That's how it's supposed to work from a high level, but implementations vary in how they implement this. Some require the library to be setup in particular way. For example, a PHP validator I've used requires you to register all your schemas into a SchemaStore before they can be referenced.

Reference: http://json-schema.org/latest/json-schema-core.html#anchor27