JSON模式枚举可以不区分大小写吗?

问题描述 投票:7回答:2

JSON Schema enums

JSON Schemas feature enums, which impose a constraint on the values of a string type

{
    "type": "array",
    "items": [
        {
            "type": "number"
        },
        {
            "type": "string"
        },
        {
            "type": "string",
            "enum": ["Street", "Avenue", "Boulevard"]
        },
        {
            "type": "string",
            "enum": ["NW", "NE", "SW", "SE"]
        }
    ]
}

此模式验证[1600, "Pennsylvania", "Avenue", "NW"]等值。

The problem

是否有一种优雅的方法使enum不区分大小写,以便Avenueavenue都被接受为数组中的第三个值?

Other possible solutions

我可以在值列表中使用anyOf,并根据不区分大小写的正则表达式验证每个值 - 但这很麻烦,容易出错并且不优雅。

enums case-insensitive jsonschema
2个回答
5
投票

我担心你找不到任何优雅的解决方案。有一个关于case-insensitive enums and several issues were commented的提案。

因此,如果您无法避免这种要求,那么正则表达式解决方案是唯一可行的解​​决方案。另一种蛮力方法是拥有n个完整的枚举值列表,一个带有起始大写字母,另一个带有大写字母等,然后按照你的说法使用anyOf。您可以轻松地自动创建此json-schema。显然它不会很可读。

无论如何,我会尝试在验证之前通过预处理步骤来解决这个问题。如果存在,您可以将所需属性转换为小写,然后进行验证。我发现有点被迫使用json-schema规范来允许“脏”数据。


0
投票

我最终创建了2个帮助器,将字符串转换为不区分大小写的模式,并将它们转换回小写版本:

const toCaseInsensitive = (v = "") =>
    v
        .split("")
        .map(l => {
            const lower = l.toLowerCase()
            const upper = l.toUpperCase()
            return lower === upper ? lower : `[${lower}|${upper}]`
        })
        .join("")
const fromCaseInsensitive = (v = "") => v.replace(/\[(.)\|(.)\]/g, "$1")

用法:

toCaseInsensitive("TeSt") -> "[t|T][e|E][s|S][t|T]"
fromCaseInsensitive("[t|T][e|E][s|S][t|T]") -> "test"

© www.soinside.com 2019 - 2024. All rights reserved.