例如... import osimport jsonfrom jsonschema import Draft4Validator, RefResolver # We prefer Draft7, but jsonschema 3.0 is still in alpha as of this writing abs_path_to_schema = '/path/to/schema-doc-foobar.json'with open(abs_path_to_schema, 'r') as fp: schema = json.load(fp)resolver = RefResolver( # The key part is here where we build a custom RefResolver # and tell it where *this* schema lives in the filesystem # Note that `file:` is for unix systems schema_path='file:{}'.format(abs_path_to_schema), schema=schema)Draft4Validator.check_schema(schema) # Unnecessary but a good ideavalidator = Draft4Validator(schema, resolver=resolver, format_checker=None)# Then you can...data_to_validate = `{...}`validator.validate(data_to_validate)I have a set of jsonschema compliant documents. Some documents contain references to other documents (via the $ref attribute). I do not wish to host these documents such that they are accessible at an HTTP URI. As such, all references are relative. All documents live in a local folder structure. How can I make python-jsonschema understand to properly use my local file system to load referenced documents?For instance, if I have a document with filename defs.json containing some definitions. And I try to load a different document which references it, like:{ "allOf": [ {"$ref":"defs.json#/definitions/basic_event"}, { "type": "object", "properties": { "action": { "type": "string", "enum": ["page_load"] } }, "required": ["action"] } ]}I get an error RefResolutionError: <urlopen error [Errno 2] No such file or directory: '/defs.json'>It may be important that I'm on a linux box.(I'm writing this as a Q&A because I had a hard time figuring this out and observed other folks having trouble too.) 解决方案 You must build a custom jsonschema.RefResolver for each schema which uses a relative reference and ensure that your resolver knows where on the filesystem the given schema lives.Such as...import osimport jsonfrom jsonschema import Draft4Validator, RefResolver # We prefer Draft7, but jsonschema 3.0 is still in alpha as of this writing abs_path_to_schema = '/path/to/schema-doc-foobar.json'with open(abs_path_to_schema, 'r') as fp: schema = json.load(fp)resolver = RefResolver( # The key part is here where we build a custom RefResolver # and tell it where *this* schema lives in the filesystem # Note that `file:` is for unix systems schema_path='file:{}'.format(abs_path_to_schema), schema=schema)Draft4Validator.check_schema(schema) # Unnecessary but a good ideavalidator = Draft4Validator(schema, resolver=resolver, format_checker=None)# Then you can...data_to_validate = `{...}`validator.validate(data_to_validate) 这篇关于如何在python-jsonschema文档中设置本地文件引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-23 15:13