Search code examples
pythonjsonjsonschemapython-jsonschema

JSON with Python: No expected validation errors with jsonschema


I have defined a schema and used it to validate JSON objects but I never get the expected ValidationError. For example:

>>> from jsonschema import validate
>>> schema = {
...   "type" : "object",
...   "properties" : {
...       "address" : {"type" : "string"},
...    },
... }
>>>
>>> schema
{'type': 'object', 'properties': {'address': {'type': 'string'}}}
>>> validate(instance={"address" : "123 Main St.", "price" : 34.99}, schema=schema)
>>> validate(instance={"address1" : "123 Main St.", "price" : 34.99}, schema=schema)
>>>
>>> validate(instance={"addresdvzdvfafczscss1" : "123 Main St.", "price" : 34.99}, schema=schema)
>>> validate(instance={"addresdvzdvfafczscss1" : "123 Main St.", "price" : 34.99}, schema=schema)
# doctest: +IGNORE_EXCEPTION_DETAIL
>>>
>>> validate(instance={"addresdvzdvfafczscss1" : "123 Main St.",}, schema=schema)  # doctest: +IGNO
RE_EXCEPTION_DETAIL
>>>
>>> type(schema)
<class 'dict'>
>>> str(schema)
"{'type': 'object', 'properties': {'address': {'type': 'string'}}}"
>>> validate(instance={"addresdvzdvfafczscss1" : 123,}, schema=schema)  # doctest: +IGNORE_EXCEPTIO
N_DETAIL
>>>

Can anyone see what I'm doing wrong?


Solution

  • You didn't say what you expected to get as an error, but I'm going to guess that you want the validation to complain that the "address" property is missing. To achieve that, you need to use the required keyword, so try:

    {
      "type": "object",
      "required": [ "address" ],
      "properties": {
        "address": {"type": "string"}
      }
    }
    

    You may also want to say "no other properties other than address are permitted" -- which can be done with "additionalProperties": false.