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

标签 python json jsonschema

假设我有一个名为 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;爷爷指的是 parent 使用“$ref”:“file:parent.json, parent 指的是 child 使用“$ref”:“file:child.json。那么上面的相对路径就不行了

最佳答案

构建github issue由@jruizaranguren 链接,我最终得到了以下按预期工作的结果:

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)

关于python - 如何在 Json Schema 中使用 $ref 的相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24938255/

相关文章:

Python timedelta用pandas中的字符串替换0时间

python - 在 Python 中分解三阶张量

asp.net - ASP.net JSON Webservice 响应类型的问题

javascript - 如何只选择一些 JSON 对象?

javascript - 为什么我的 JSON 获取查询返回未定义的值?

python - 导入错误 : cannot import name 'validate' from jsonschema

JSON Schema 嵌套 If Then

python - Selenium:使用 Python 获取元素的坐标或尺寸

Python使用多处理将图像读取到numpy数组

jsonschema - JSON 模式排除属性(与必需属性相反)