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

jruizaranguren
  • 12,679
  • 7
  • 55
  • 73
jay_t
  • 3,593
  • 4
  • 22
  • 27

1 Answers1

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)
Rob Wouters
  • 15,797
  • 3
  • 42
  • 36