I have recently started exploring JSON Schema for one of our project. The use case is very straight forward and after lot of googling I am still not able to make it work. Actually I am little bit lost here. . This is what I tried https://json-schema.org/understanding-json-schema/structuring.html
My 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" }
}
}
Now my server_update.json
schema , where I want to validate 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"
}
}
}
But when I am trying to validate server_update.json
schema using jsonschema
https://python-jsonschema.readthedocs.io/en/stable/ it doesn't consider the $ref
schema common_data_schema.json
definitions
The schema loader
logic is straight forward, all my schemas are residing inside artifacts
folder
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)
The json schema
validation logic below
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))