如何在Json Schema中使用相对路径作为$ref?

4

假设我有一个名为 child.json 的 JSON 模式。

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

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

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

我的问题是:如果我有三个模式:grandpa.json、parent.json 和 child.json;grandpa 使用 "$ref": "file:parent.json" 引用 parent,而 parent 使用 "$ref": "file:child.json" 引用 child。那么上述相对路径就无法再次工作了。


似乎这个问题已经在以下 Github 问题中得到解决:https://github.com/Julian/jsonschema/issues/98 - jruizaranguren
我已经阅读了这篇文章。这是否意味着我必须在某个地方指定绝对路径(可能是在我的模式或验证器内部)?我不能直接使用相对路径吗? - ahri
我不这么认为。根据帖子中的评论,这是一个文件加载和引用解析的问题。其中一个人甚至已经建立了一个小工具来进行去引用操作:https://github.com/gazpachoking/jsonref。你尝试过他们在帖子中提到的方法吗? - jruizaranguren
@nishant 我不知道这是否有效。我已经在 GitHub 和这里阅读了您关于相同问题的帖子。希望您能帮助我解决这个问题。 - ahri
1个回答

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 contains a line like this: "$schema": "http://json-schema.org/draft-04/schema#"
jsonschema.validate(data, schema, resolver=resolver)

1
这是正确的,只是open调用缺少一个闭合括号。 - Nico7as

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接