如何在Json架构中为$ref使用相对路径

2024-09-30 01:33:43 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个名为child.json文件. 在

“$ref”:文件:child.json“会有用的

“$ref”:文件:./child.json“会有用的

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

我的问题是:如果我有3个模式:爷爷.json, 父级.json,和child.json文件;爷爷指的是使用“$ref”的家长:文件:parent.json和父项使用“$ref”引用子项:文件:child.json。那么上面的相对路径就不起作用了


Tags: 文件comrefjsonchildhttp模式parent
1条回答
网友
1楼 · 发布于 2024-09-30 01:33:43

以@jruizarangureni链接的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)

相关问题 更多 >

    热门问题