Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python jsonschema validation fails when additionalProperties is set to false

I'm trying to define a schema inside a python script, to be used right away to validate some json data. the schema definition looks like this:

    response_schema = {
    "required": ["identifiers" ],
    "properties": {
        "identifiers": {
          "minProperties": 1,"maxProperties": 1,
          "additionalProperties": {
            "required": [  "name","surname" ],
            "properties": {
              "surname": {
                  "required": ["sur1", "sur2" ],
                  "properties": {
                     "sur1": { },
                     "sur2": { }
              } },
              "name": {},

            "additionalProperties": false
            }
          }
        }
      },
    "additionalProperties": false
}

That schema works fine in any online validator, but when I execute the validation in my script:

validate(response_body_dict, response_schema)

I get the following error:

NameError: name 'false' is not defined

If I remove the lines "additionalProperties" : false from the schema I don't get the error, but of course it doesn't work for me, as it is a much less restrictive validation.

Can anyone please explain why I am getting this error?

like image 980
mtnezdilarduya Avatar asked Nov 08 '22 01:11

mtnezdilarduya


1 Answers

The problem is a difference between Python and JSON. In Python you spell it 'False' and in JSON you spell it 'false'.

If you copy your schema into a text file and load it with the json module it will work correctly - no error.

When you load this snippet of code in a Python program you get the error you provided because Python does not know what 'false' is. The code is creating a dictionary, not a JSON schema.

If you want to prototype in place you could wrap it in """ and then use json.loads.

Like this:

import json
response_schema_str = """{
    "required": ["identifiers" ],
    "properties": {
        "identifiers": {
            "minProperties": 1,
            "maxProperties": 1,
            "additionalProperties": {
                "required": [
                    "name",
                    "surname" ],
                "properties": {
                    "surname": {
                        "required": [
                            "sur1",
                            "sur2" ],
                        "properties": {
                            "sur1": { },
                            "sur2": { }
                        }
                    },
                    "name": {},
                    "additionalProperties": false
                }
            }
        }
    },
    "additionalProperties": false
}"""
response_schema = json.loads(response_schema_str)
print(response_schema)
like image 135
ChipJust Avatar answered Nov 15 '22 12:11

ChipJust