【问题标题】:Python jsonschema fails to validate enum of stringsPython jsonschema 无法验证字符串的枚举
【发布时间】:2014-09-18 15:17:46
【问题描述】:

所以,我正在尝试为一组轴约束定义一个模式。因此,我想将“axis”元素的可能值限制为[“x”,“y”,“z”]。

这是我当前的示例,它是输出。

JSON:

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

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

架构:

{
    "$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"]
        }

    }
}

如何修复我的架构以拒绝未在枚举器中指定的值?

【问题讨论】:

    标签: python json enums jsonschema


    【解决方案1】:

    您的架构语法有点偏离。

    首先,您需要将属性定义放入properties

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

    其次,type 定义了类型(例如"string"),但这里不需要它。 enum 应该直接在 "axis" 架构内:

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

    【讨论】:

    • 奇怪。我已经直接测试了该示例,并且可以正常工作。当我在更大的架构中进行更改时,它没有。我添加了完整的架构和 JSON。你介意再看一下吗?
    • anyOf 中需要一个大写“O”。 :)
    猜你喜欢
    • 1970-01-01
    • 2022-12-16
    • 1970-01-01
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 2020-02-24
    • 2018-10-13
    相关资源
    最近更新 更多