本文介绍了在python draft7中的jsonschema中从$ ref创建ref-resolver的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有json模式
{
"$id": "d:/documents/schemaFiles/WLWorkProduct/1",
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "WLWorkProduct",
"description": "",
"type": "object",
"properties": {
"RID": {
"description": "resource type.",
"type": "string"
},
"Data": {
"type": "object",
"properties": {
"IndividualTypeProperties": {
"allOf": [
{
"$ref": "d:/documents/schemaFiles/WorkProduct/1"
},
{
"type": "object",
"properties": {
"WID": {
"type": "string",
"description": "WID"
}
}
}
]
}
}
}
},
"additionalProperties": false
}
我正在尝试为这种类型的架构构建refresolver,其中$ ref引用不同目录中的另一个json文件.这是我尝试过的代码
I am trying to build refresolver for this type of schema where $ref refers to another json file in different directory. Here is the code I tried
import os
import pathlib
import json
from jsonschema import Draft7Validator, FormatChecker, ValidationError, SchemaError, validate, RefResolver, exceptions
BASE_DIR='d:/documents/schemaFiles'
schemaPath='d:/documents/schemaFiles'
json_file='d:/documents/results/OutawsLog.json' #API output
def _validate(schema_search_path, json_data, schema_id):
"""
load the json file and validate against loaded schema
"""
try:
schemastore = {}
fnames=[]
for roots, _, files in os.walk(schema_search_path):
for f in files:
if f.endswith('.json'):
fnames.append(os.path.join(roots, f))
for fname in fnames:
with open(fname, "r") as schema_fd:
schema = json.load(schema_fd)
if "$id" in schema:
print("schema[$id] : ", schema["$id"])
schemastore[schema["$id"]] = schema
test_schema_id='d:/documents/schemaFiles/WLWorkProduct/1'
schema = schemastore.get(test_schema_id)
Draft7Validator(schema)
resolver = RefResolver(BASE_DIR, "file://{0}".format(os.path.join(BASE_DIR, '/WLWorkProduct.json')), schema, schemastore)
try:
v=Draft7Validator(schema, resolver=resolver).iter_errors(json_data)
print("v : ", v)
for error in v:
print(error.message)
except ValidationError as e:
print(e)
except Exception as error:
# handle validation error
print(error)
except SchemaError as error:
print(error)
return False
def getData(jsonFile):
with open(jsonFile) as fr:
dt=json.loads(fr.read())['results']['results']
return dt
json_dt=getData(json_file)
for jd in json_dt[:1]:
print(type(jd))
_validate(schemaPath, jd, 1)
对于$ ref参考,它给我带来了关键错误
It gives me key error for $ref reference as
- jsonschema.exceptions.RefResolutionError:
- KeyError:'d:/documents/schemaFiles/WorkProduct/1'
我认为我在创建refresolver时缺少了一些东西.任何帮助将不胜感激..
I think I am missing something while creating refresolver. Any help would be appreciated..
推荐答案
请尝试执行以下操作:"$ ref":"d:/documents/schemaFiles/WorkProduct#/1"如果要使用在其中定义的"1"类型WorkProduct.json.
please try this: "$ref": "d:/documents/schemaFiles/WorkProduct#/1" if you want to use "1" type defined in WorkProduct.json.
希望它可以提供帮助!
这篇关于在python draft7中的jsonschema中从$ ref创建ref-resolver的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!