Peaches491
Peaches491

Reputation: 1239

Python jsonschema fails to validate enum of strings

So, I'm trying to define a schema for a set of axis constraints. Therefore, I would like to restrict the possible values of the "axis" element to ["x", "y", "z"].

Here is my current sample, and it's output.

JSON:

{
    "name_patterns": [
        {
            "regex": "block[_-]?([\\d]*)",
            "class": "block",
            "id_group": 1
        }
    ],

    "relationships": [
        {
            "src_class": "block",
            "dst_class": "block",
            "constraints": {
                "axis": "x"
            }
        }
    ]
}

Schema:

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "properties": {
        "name_patterns": {"type":  "array",
                          "items": { "$ref": "#/definitions/name_entry" } },
        "relationships": {"type":  "array",
                          "items": { "anyof": [ {"$ref": "#/definitions/relation"} ] } }
    },

    "definitions": {
        "name_entry": {
            "type": "object",
            "properties": {
                "regex": {"type": "string"},
                "class": {"type": "string"},
                "id_group": {"type": "number"}
            },
            "required": ["regex", "class"]
        },
        "relation": {
            "type": "object",
            "properties": {
                "src_class": {"type": "string"},
                "dst_class": {"type": "string"},
                "constraints": {
                    "type": "object",
                    "properties": {
                        "axis": {
                            "enum": ["x", "y", "z"]
                        }
                    },
                    "required": ["axis"]
                }
            },
            "required": ["src_class", "dst_class", "constraints"]
        }

    }
}

How can I fix my schema to reject values which are not specified in the enumerator?

Upvotes: 2

Views: 5796

Answers (1)

cloudfeet
cloudfeet

Reputation: 12882

Your schema syntax is a bit off.

Firstly, you need to put property definitions inside properties:

{
    "properties": {
        "axis": {...}
    }
}

Secondly, type defines the type (e.g. "string"), but you don't need it here. enum should just be directly inside the "axis" schema:

{
    "properties": {
        "axis": {
            "enum": ["x", "y", "z"]
        }
    }
}

Upvotes: 6

Related Questions