I am using python 2.7 jsonschema validate method to validate a response json against jsonSchema.
My jsonSchema is a dictionary as follows:
schema = {
"type" : "object",
"properties" : {
"Country": {"type": "object",
"properties":{
"State" : { "type" : "object",
"properties": {
"city": {"type": "object",
"properties":{
"lat":{"type": "string"},
"long": {"type": "string"}
}
},
"StateCode": {"type": "string"},
"StateFlagColor111": {"type": "string"},
"StateCapital": {"type": "string"}
}
}
}
}
}
}
My response json that I am trying to validate against this Schema is
{
"Country": {
"State": {
"City": {
"lat": "PP_4001",
"long": "Invalid GlobalParameters"
},
"StateCode": "2017-06-16 18:15:14.442000",
"StateFlagColor": "400",
"StateCapital": "ERROR"
}
}
}
Python code snippet to validate json data against json schema is
import jsonschema
from jsonschema import validate
try:
validate(responseDataJson, schema)
print 'good json'
except jsonschema.exceptions.ValidationError as ve:
print 'bad json' + str(ve)
If you see in the schema, name of the element is StateFlagColor111 and element in json data is stageFlagColor. I am not sure how does it not throw an exception for such a validation. It always passes.
Then, out of curiosity, i created a very basic jsonSchema like this a tried to validate the same josn data as above against this new schema.
schema1 = {
"type": "object",
"properties":{
"x1":{"type":"string"}
}
}
jsondata got validated against this simple schema also.
I am not sure what am I missing here. How should I make this work ?
By default, a schema will allow objects to contain other properties that you have not explicitly specified. You need to add "additionalProperties": False at both top level and inside the sub-objects - State and City - to disable this.
Also, your schema does not have any required properties. Again, if you want any property to be required, you need required arrays at the appropriate levels.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With