gpt4 book ai didi

json - Python Json 引用和验证

转载 作者:行者123 更新时间:2023-12-01 05:28:54 24 4
gpt4 key购买 nike

我开始使用 python 来验证一些 json 信息,我正在使用带有引用的 json 模式,但我无法引用这些文件。这是代码:

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 文件夹中:

录音.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"]}

艺术家.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"]}

这是我的错误:

Connected to pydev debugger (build 181.5281.24)
Traceback (most recent call last):
File "C:\Python\lib\site-packages\proxytypes.py", line 207, in __subject__
return self.cache
File "C:\Python\lib\site-packages\proxytypes.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:\Python\lib\site-packages\jsonref.py", line 163, in callback
base_doc = self.loader(uri)
<MORE>

python 版本:3.6.5

window 7

想法:智能想法

有人可以帮助我吗?谢谢

最佳答案

我不确定为什么,但在 Windows 上,file:// 需要额外的 /。因此,以下更改应该可以解决问题

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

从为相关 issue 发布的解决方案得出此答案在 json 模式中

关于json - Python Json 引用和验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51275554/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com