如何在Json Schema中使用$ref的相对路径

4 投票
1 回答
5616 浏览
提问于 2025-04-18 14:37

假设我有一个叫做 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。那么上面提到的相对路径就不再有效了。

1 个回答

1

根据@jruizaranguren提到的GitHub问题,我得到了以下代码,运行效果如我所预期的那样:

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)

撰写回答