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

时间:2014-07-24 15:43:12

标签: 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;爷爷指父母使用" $ ref":"文件:parent.json,父母指的是使用" $ ref":"文件:child的孩子。 JSON。然后上面的相对路径不再起作用

1 个答案:

答案 0 :(得分:0)

以@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)
相关问题