Python Json引用和验证



我开始使用python来验证一些json信息,我使用的是带有引用的json模式,但我在引用这些文件时遇到了麻烦。这是code:

from os.path import join, dirname
from jsonschema import validate
import jsonref
def assert_valid_schema(data, schema_file):
""" Checks whether the given data matches the schema """
schema = _load_json_schema(schema_file)
return validate(data, schema)
def _load_json_schema(filename):
""" Loads the given schema file """
relative_path = join('schemas', filename).replace("\", "/")
absolute_path = join(dirname(__file__), relative_path).replace("\", "/")
base_path = dirname(absolute_path)
base_uri = 'file://{}/'.format(base_path)
with open(absolute_path) as schema_file:
return jsonref.loads(schema_file.read(), base_uri=base_uri, jsonschema=True, )
assert_valid_schema(data, 'grandpa.json')

json数据为:

data = {"id":1,"work":{"id":10,"name":"Miroirs","composer":{"id":100,"name":"Maurice Ravel","functions":["Composer"]}},"recording_artists":[{"id":101,"name":"Alexandre Tharaud","functions":["Piano"]},{"id":102,"name":"Jean-Martial Golaz","functions":["Engineer","Producer"]}]}

我正在将模式和引用文件保存到schemas文件夹中:

recording.json:

{"$schema":"http://json-schema.org/draft-04/schema#","title":"Schema for a recording","type":"object","properties":{"id":{"type":"number"},"work":{"type":"object","properties":{"id":{"type":"number"},"name":{"type":"string"},"composer":{"$ref":"artist.json"}}},"recording_artists":{"type":"array","items":{"$ref":"artist.json"}}},"required":["id","work","recording_artists"]}

artist.json:

{"$schema":"http://json-schema.org/draft-04/schema#","title":"Schema for an artist","type":"object","properties":{"id":{"type":"number"},"name":{"type":"string"},"functions":{"type":"array","items":{"type":"string"}}},"required":["id","name","functions"]}

这是我的error:

Connected to pydev debugger (build 181.5281.24)
Traceback (most recent call last):
File "C:Pythonlibsite-packagesproxytypes.py", line 207, in __subject__
return self.cache
File "C:Pythonlibsite-packagesproxytypes.py", line 131, in __getattribute__
return _oga(self, attr)
AttributeError: 'JsonRef' object has no attribute 'cache'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:Pythonlibsite-packagesjsonref.py", line 163, in callback
base_doc = self.loader(uri)
<MORE>

python版本:3.6.5

windows 7

Ide:intellijIdea

有人能帮我吗?谢谢

我不知道为什么,但在Windows上,file://需要一个额外的/。因此,下面的改变应该可以实现

base_uri = 'file:///{}/'.format(base_path)

从json模式中发布的相关问题的解决方案中得出了这个答案

最新更新