19

我有 3 个模式:

子架构:

{
    "title": "child_schema",
    "type": "object",
    "properties": {
        "wyx":{
            "type": "number"
        }
     },
    "additionalProperties": false,
    "required": ["wyx"]
}

父架构:

{
    "title": "parent",
    "type": "object",
    "properties": {
        "x": {
            "type": "number"
        },
        "y": {
            "type": "number"
        },
        "child": {
            "$ref": "file:child.json"
        }
    }
}

爷爷架构:

{
    "type": "object",
    "title": "grandpa",
    "properties": {
        "reason": {
            "$ref": "file:parent.json"
        }
    },
    "additionalProperties": false
}

如您所见, gradpa 对 parent 有一个 ref,而 parent 对 child 有一个 ref。所有这 3 个文件都在同一个文件夹中。当我使用 python 验证器验证爷爷模式时,我会不断收到一个名为 RefResolutionError 的错误。

但是,如果我没有爷爷,我只使用父模式和子模式,一切正常!!所以问题是我不能有一个 ref 指向一个 ref(2 个级别)。但我可以有一个指向模式的参考(只有 1 级。)

我想知道为什么

4

2 回答 2

22

你的引用不正确。如果引用的方案位于同一文件夹中,请使用简单的相对路径引用,例如:

    "child": {"$ref": "child.json"},
    "reason": {"$ref": "parent.json"}

如果您使用jsonschema进行验证,请不要忘记设置引用解析器以解析引用模式的路径:

    import os
    from jsonschema import validate, RefResolver
    
    instance = {}
    schema = grandpa

    # this is a directory name (root) where the 'grandpa' is located
    schema_path = 'file:///{0}/'.format(
          os.path.dirname(get_file_path(grandpa)).replace("\\", "/"))
    resolver = RefResolver(schema_path, schema)
    validate(instance, schema, resolver=resolver)
于 2015-10-14T12:12:20.640 回答
0

这就是我用来从给定目录中的所有模式动态生成jsonschema的方法 schema_store

child.schema.json

{
    "$id": "child.schema.json",
    "title": "child_schema",
    "type": "object",
    "properties": {
        "wyx":{
            "type": "number"
        }
     },
    "additionalProperties": false,
    "required": ["wyx"]
}

parent.schema.json

{   
    "$id": "parent.schema.json",
    "title": "parent",
    "type": "object",
    "properties": {
        "x": {
            "type": "number"
        },
        "y": {
            "type": "number"
        },
        "child": {
            "$ref": "child.schema.json"
        }
    }
}

instance.json

{
    "x": 1,
    "y": 2,
    "child": {
        "wyx": 3
    }
}

validator.py

import json

from pathlib import Path

from jsonschema import Draft7Validator, RefResolver
from jsonschema.exceptions import RefResolutionError

schemas = (json.load(open(source)) for source in Path("schema/dir").iterdir())
schema_store = {schema["$id"]: schema for schema in schemas}

schema = json.load(open("schema/dir/extend.schema.json"))
instance = json.load(open("instance/dir/instance.json"))
resolver = RefResolver.from_schema(schema, store=schema_store)
validator = Draft7Validator(schema, resolver=resolver)

try:
    errors = sorted(validator.iter_errors(instance), key=lambda e: e.path)
except RefResolutionError as e:
    print(e)
于 2022-01-21T07:15:53.420 回答