【问题标题】:JSON Schema required field depending on other field valueJSON Schema 必填字段取决于其他字段值
【发布时间】:2019-10-03 17:07:28
【问题描述】:

是否可以根据 JSON 模式中的其他字段值使字段为必填/非必填?

JSON 架构包含 mode 字段。如果它等于 'release' 或 'debug',则不需要 file_path。如果它等于 'custom' 它是必需的。

"mode": {
    "enum": [
        "debug",
        "release",
        "custom"
    ],
    "id": "mode",
    "required": true,
    "type": "string"
},
"file_path": {
    "id": "file_path",
    "required": false,
    "type": "string"
}

【问题讨论】:

    标签: json validation schema


    【解决方案1】:

    JSON Schema Draft 7 有一个解决方案:

    {
        "build": {
            "type": "object",
            "id": "build",
    
            "oneOf": [
                {
                    "$ref": "#/definitions/ReleaseDebug"
                },
                {
                    "$ref": "#/definitions/Custom"
                }
            ]
        }
    },
    "definitions": {
        "ReleaseDebug": {
            "required": ["mode"],
            "properties": {
                "mode": {
                    "type": "string",
                    "enum": [
                        "debug",
                        "release"
                    ],
                    "id": "mode"
                }
            }
        },
        "Custom": {
            "required": ["mode", "file_path"],
            "properties": {
                "mode": {
                    "type": "string",
                    "enum": [
                        "custom"
                    ],
                    "id": "mode"
                },
                "file_path": {
                    "type": "string",
                    "id": "file_path"
                },
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-12
      • 2016-01-20
      • 1970-01-01
      • 2016-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多