【问题标题】:Validating Mandatory String values in JSON Schema验证 JSON 模式中的强制字符串值
【发布时间】:2017-09-01 09:14:18
【问题描述】:

我有以下示例架构。我需要确保在 json 文件中至少出现一次“name”:“This is Mandatory”

有可能做到这一点吗?请帮忙。

   "SchemaList": {
      "type": "array",      
      "additionalItems": false,
      "items": { "$ref": "#/definitions/Schema1" }          
        },
   "Schema1": {
      "type": "object",         
      "properties": {
        "description": { "type": "string" },
        "name": { "type": "string" }        
            }
        }

【问题讨论】:

    标签: json jsonschema json-schema-validator


    【解决方案1】:

    最新的草案(草案 6)引入了一个新的关键字 "contains" ,您可以使用它来表示给定的架构应该至少匹配数组中的一个元素。你可以这样使用它:

    {
        "SchemaList": {
            "additionalItems": false,
            "contains": {
                "properties": {
                    "name": {
                        "const": "This is Mandatory"
                    }
                },
                "required": [
                    "name"
                ]
            },
            "items": {
                "$ref": "#/definitions/Schema1"
            },
            "type": "array"
        }
    }
    

    但请记住 the latest draft version of json-schema has only a very few implementations ,因此根据您使用的库,"contains" 关键字可能不起作用。

    【讨论】:

    • 非常感谢@erosb 这正是我想要的。我之前确实尝试过“包含”,但还没有意识到它从 v6 开始就有效。顺便说一句,我在 Swagger 2.0(使用 V4)中使用它。无论如何,这非常有帮助。玩得开心:)
    【解决方案2】:

    更多详情请参考此链接:http://json-schema.org/example1.html

    {
    "SchemaList": {
        "type": "array",
        "additionalItems": false,
        "items": {
            "$ref": "#/definitions/Schema1"
        }
    },
    "Schema1": {
        "type": "object",
        "properties": {
            "description": {
                "type": "string"
            },
            "name": {
                "type": "string"
            }
        }
    },
    "required": ["name"]
    }
    

    【讨论】:

    • 在上面的例子中,必须声明“name”,但不能强制name的值。我不能使用枚举,因为我需要 name 的动态值,并且它应该要求 name: "ThisIsMandatory" 至少出现一次。为了更清楚,我需要验证名称的值。
    • 您正在尝试获取名称值并需要对其进行处理?
    猜你喜欢
    • 2021-11-28
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多