Jsonschema RefResolver 解析 python 中的多个引用

rep*_*rev 2 python jsonschema

我们如何使用 jsonschema.RefResolver 验证模式中的多个引用?

我有一个验证脚本,如果我在文件中有一个引用,它就可以很好地工作。我现在在一个架构中有两个或三个引用,它们位于不同的目录中。

base_dir = '/schema/models/'
with open (os.path.join(base_dir, 'Defined.json')) as file_object:
    schema = json.load(file_object)
    resolver = jsonschema.RefResolver('file://' + base_dir + '/' + 'Fields/Ranges.json', schema)
    jsonschema.Draft4Validator(schema, resolver=resolver).validate(data)
Run Code Online (Sandbox Code Playgroud)

我的 json 架构:

{
  "properties": {
    "description": {
        "type": "object",
        "after": {"type": ["string", "null"]},
        "before": {"type": "string"}
      },
      "width": {"type": "number"} ,
      "range_specifier": {"type": "string"},
      "start": {"type": "number", "enum" : [0, 1] } ,
      "ranges": {
        "$ref": "Fields/Ranges.json"
      },
      "values": {
        "$ref": "Fields/Values.json"
      }
  }
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是我应该有两个解析器,一个用于范围,一个用于值,并在 Draft4Validator 中分​​别调用解析器?或者有没有更好的方法来做到这一点?

小智 8

我自己在同一个问题上花了几个小时,所以我希望这个解决方法对其他人有用

def validate(schema_search_path, json_data, schema_id):
    """
    load the json file and validate against loaded schema
    """
    try:
        schemastore = {}
        schema = None
        fnames = os.listdir(schema_search_path)
        for fname in fnames:
            fpath = os.path.join(schema_search_path, fname)
            if fpath[-5:] == ".json":
                with open(fpath, "r") as schema_fd:
                    schema = json.load(schema_fd)
                    if "id" in schema:
                        schemastore[schema["id"]] = schema

        schema = schemastore.get("http://mydomain/json-schema/%s" % schema_id)
        Draft4Validator.check_schema()
        resolver = RefResolver("file://%s.json" % os.path.join(schema_search_path, schema_id), schema, schemastore)
        Draft4Validator(schema, resolver=resolver).validate(json_data)
        return True
    except ValidationError as error:
        # handle validation error 
        pass
    except SchemaError as error:
        # handle schema error
        pass
    return False
Run Code Online (Sandbox Code Playgroud)

应该在路径解析中使用的每个 JSON 模式都有一个 ID 元素,必须将其作为schema_id参数传递以进行验证

  "id": "http://mydomain/json-schema/myid"
Run Code Online (Sandbox Code Playgroud)

所有模式都加载到字典中,然后作为存储传递给解析器。在您的示例中,您还应该从其他目录加载架构。