I have a problem, and ai don't know how start.
I have a json example:
{
"vcn_keys": {
"name_1": {
"compartment_id": "ocid1.compartment.oc1..jlq",
"cidr": "11.0.0.0/16",
"subnets": {
"sub_poc1_1": {
"compartment_id": "ocid1.compartment.oc1..jlq",
"name": "sub_vcn1_1",
"cidr": "10.0.0.0/24"
}
}
},
"name_2": {
"compartment_id": "ocid1.compartment.oc1..jlq",
"cidr": "10.0.0.0/16",
"subnets": {
"sub_poc2_1": {
"compartment_id": "ocid1.compartment.oc1..jlq",
"name": "sub_vcn2_1",
"cidr": 456
}
}
}
}
}
and a jsonschema for this json example:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "User",
"description": "A user request json",
"type": "object",
"properties": {
"vcn_keys": {
"type": "object",
"patternProperties": {
"[a-zA-Z0-9_]+": {
"type": "object",
"properties": {
"compartment_id": {
"description": "ocid info",
"type": "string"
},
"cidr": {
"description": "cdir range",
"type": "string"
},
"subnets": {
"type": "object",
"patternProperties": {
"[a-zA-Z0-9_]+": {
"type": "object",
"properties": {
"compartment_id": {
"description": "ocid info",
"type": "string"
},
"name": {
"description": "ocid info",
"type": "string"
},
"cidr": {
"description": "cdir range",
"type": "string"
}
}
}
}
}
}
}
}
}
}
}
I test it on this page : https://jsonschema.dev/s/LMl3N
And it's working, for example if a change a value inside subnet object to number instead string ... it WORKS
How i can so the same with PYTHON?
update
this is my first draft, but it doesn't work, don't show me the error:
import json
import jsonschema
from jsonschema import validate
def get_schema():
with open('schema_v6.json', 'r') as file:
schema = json.load(file)
return schema
def validate_json(json_data):
execute_api_schema = get_schema()
try:
validate(instance=json_data, schema=execute_api_schema)
except jsonschema.exceptions.ValidationError as err:
print(err)
err = "Given JSON data is InValid"
return False, err
message = "Given JSON data is Valid"
return True, message
f = open('sample_v7.json')
data = json.load(f)
for i, obj in enumerate(data['vcn_keys']):
try:
# validate(instance=obj, schema=schema)
print(data)
validate_json(data)
except Exception as e:
print(f"obj {i} invalid: {e}")
else:
print(f"obj {i} valid")
for obj in data['vcn_keys']:
print(data)
Regards