我最近开始为我们的一个项目探索 JSON Schema。用例非常简单,经过大量谷歌搜索后,我仍然无法使其工作。其实我有点迷失在这里。. 这就是我尝试过的https://json-schema.org/understanding-json-schema/structuring.html
我的common_data_schema.json
{
"definitions": {
"sp_common_data": {
"type": "object",
"properties": {
"os_ip": {
"type": "string",
"format": "ipv4"
},
"os_user": {
"type": "string"
},
"os_pwd": {
"type": "string"
},
"remote_os": {
"default": "Windows",
"enum": [
"Linux",
"Windows"
]
}
},
"required": [
"os_ip",
"os_user",
"os_pwd",
"remote_os"
]
} },
"type": "object",
"properties": {
"sp_must_data":{ "$ref": "#/definitions/sp_common_data" }
}
}
现在我的server_update.json
架构,我想验证common_data_schema
+new
properties
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"sp_must_data":{"$ref": "common_data_schema.json#sp_common_data"},
"file": {
"type": "string"
}
}
}
但是,当我尝试使用https://python-jsonschema.readthedocs.io/en/stable/server_update.json
验证架构时,它不会考虑架构定义jsonschema
$ref
common_data_schema.json
schema loader
逻辑很简单,我所有的模式都驻留在 文件artifacts
夹中
import json
from pathlib import Path
# Location for the test artifacts
artifacts = Path(__file__).parent.parent.joinpath("artifacts").resolve()
def load_schema(filename):
data = open(Path(artifacts).joinpath(filename), "r").read()
return json.loads(data)
下面的json schema
验证逻辑
from typing import Dict, List
from jsonschema import Draft7Validator, exceptions
def validate(schema: Dict, instance: Dict) -> List[exceptions.ValidationError]:
"""
Validate the instance using the specified schema
:param schema: Schema object
:param instance: instance Object
:return: List of errors during validation
"""
validator = Draft7Validator(schema=schema)
return list(validator.iter_errors(instance))