10

I'm dealing with data input in the form of json documents. These documents need to have a certain format, if they're not compliant, they should be ignored. I'm currently using a messy list of 'if thens' to check the format of the json document.

I have been experimenting a bit with different python json-schema libraries, which works ok, but I'm still able to submit a document with keys not described in the schema, which makes it useless to me.

This example doesn't generate an exception although I would expect it:

#!/usr/bin/python

from jsonschema import Validator
checker = Validator()
schema = {
    "type" : "object",
    "properties" : {
        "source" : {
            "type" : "object",
            "properties" : {
                "name" : {"type" : "string" }
            }
        }
    }
}
data ={
   "source":{
      "name":"blah",
      "bad_key":"This data is not allowed according to the schema."
   }
}
checker.validate(data,schema)

My question is twofold:

  • Am I overlooking something in the schema definition?
  • If not, is there another lightweight way to approach this?

Thanks,

Jay

1 Answer 1

9

Add "additionalProperties": False:

#!/usr/bin/python

from jsonschema import Validator
checker = Validator()
schema = {
    "type" : "object",
    "properties" : {
        "source" : {
            "type" : "object",
            "properties" : {
                "name" : {"type" : "string" }
            },
            "additionalProperties": False, # add this
        }
    }
}
data ={
   "source":{
      "name":"blah",
      "bad_key":"This data is not allowed according to the schema."
   }
}
checker.validate(data,schema)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.