Json架构参考其他文件

时间:2017-01-06 09:10:11

标签: json file schema ref

使用此架构:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "b": {
    "type": "object",
    "properties": {
      "c": {
        "type": "string"
      }
    }
  },
  "type": "object",
  "properties": {
    "a": {
      "$ref": "#/b"
    }
  }
}

我可以验证这个例子:

{
  "a": {
    "c": "test"
  }
}

现在我想为“b”元素创建一个新的模式文件,并在我的第一个模式中引用它。我怎样才能做到这一点 ?我尝试了很多东西,但我总是得到jsonspec.reference.exceptions.NotFound:u'b.json'没有注册。

1 个答案:

答案 0 :(得分:0)

经过几个小时的谷歌搜索和各种文档阅读后,我终于成功地使用"$ref" : "file:..."撰写了两个json-schema。

我的示例数据如下所示:

john-doe.json:

{
  "first_name": "john",
  "last_name": "doe",
  "age": 42,
  "address": {
    "street_address": "foo street 42",
    "city": "baklavastan",
    "state": "foobar"
    "foo": 42
  }
}

然后我有两个json架构文件,它们位于我的文件系统的同一目录中。

customer.json

{
  "type": "object",
  "properties": {
    "first_name": { "type": "string" },
    "last_name":  { "type": "string" },
    "age" :       { "type" : "integer" },
    "address" :   { "$ref" : "file:address.json#" }
  },
  "required": ["first_name", "last_name", "age", "address"],
  "additionalProperties": false
}

address.json

{
  "type": "object",
  "properties": {
    "street_address": { "type": "string" },
    "city":           { "type": "string" },
    "state":          { "type": "string" }
  },
  "required": ["street_address", "city", "state"],
  "additionalProperties": false
}

我能够使用库Clojure(它是Java scjsv库的包装器)验证json-schema-validation中的模式

它为john-doe.json示例提供了以下验证错误(在clojure edn中):

{ :level "error",
  :schema {:loadingURI "file:address.json#", :pointer ""},
  :instance {:pointer "/address"},
  :domain "validation",
  :keyword "additionalProperties",
  :message
  "object instance has properties which are not allowed by the schema: [\"foo\"]",
  :unwanted ["foo"] }