【问题标题】:How to use relative path for $ref in Json Schema如何在 Json Schema 中使用 $ref 的相对路径
【发布时间】:2014-09-16 06:38:28
【问题描述】:

假设我有一个名为 child.json 的 json 架构。

"$ref": "file:child.json" 可以工作

"$ref": "file:./child.json" 会起作用

这是唯一对我有用的两个相对路径。我正在使用 python 验证器:http://sacharya.com/validating-json-using-python-jsonschema/

我遇到的问题是:如果我有 3 个架构:grandpa.json、parent.json 和 child.json;爷爷使用 "$ref": "file:parent.json 来指代父母,而父母使用 "$ref": "file:child.json 来指代孩子。那么上面的相对路径就不再起作用了

【问题讨论】:

  • 这似乎已在以下 github 问题中得到解决:github.com/Julian/jsonschema/issues/98
  • 我已经阅读了这篇文章。这是否意味着我必须在某处指定绝对路径(可能在我的架构内或验证器内)????我不能直接使用相对路径????
  • 我不这么认为。根据帖子中的 cmets,这是文件加载和 ref 解析的问题。其中一个甚至构建了一个用于解除引用的小工具:github.com/gazpachoking/jsonref。您是否尝试过他们在帖子中的建议?
  • @nishant 我不知道这是否可行..我已经阅读了你在 github 和这里关于同样问题的帖子。我希望你能在这方面帮助我

标签: python json jsonschema


【解决方案1】:

在@jruizaranguren 链接的github issue 的基础上,我得到了以下按预期工作的结果:

import os
import json
import jsonschema

schema_dir = os.path.abspath('resources')
with open(os.path.join(schema_dir, 'schema.json') as file_object:
    schema = json.load(file_object)

# Your data
data = {"sample": "woo!"}

# Note that the second parameter does nothing.
resolver = jsonschema.RefResolver('file://' + schema_dir + '/', None)

# This will find the correct validator and instantiate it using the resolver.
# Requires that your schema a line like this: "$schema": "http://json-schema.org/draft-04/schema#"
jsonschema.validate(data, schema, resolver=resolver)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多