JSON Schema - 根据另一个字段的值指定字段 [英] JSON Schema - specify field is required based on value of another field

查看:25
本文介绍了JSON Schema - 根据另一个字段的值指定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道模式草案 03 是否可以做到这一点.我已经让依赖项在其他地方工作,我认为可能只是需要对它们进行一些创造性的使用,以便使用它们来指定 required 属性某个领域.

Wondering if this is possible with schema draft 03. I've gotten dependencies working elsewhere, I think there is possibly just some creative use of them required in order to use them for specifying the required property of some field.

我目前的最佳尝试(不起作用)应该让您对我所追求的有所了解.我想要一个默认需要的值,当另一个字段具有特定值时是可选的.

My current best attempt (which doesn't work) should give you some idea of what I'm after. I want a value required by default, and optional when another field has a particular value.

{
    "description"   : "An address...",
    "type" : "object",
    "properties" : {
        "postcode": {
            "type" : "string",
            // postcode should be required by default
            "required" : true,      
            // postcode shouldn't be required if the country is new zealand 
            "dependencies" : {
                "country" : {
                    "enum" : ["NZ", "NZL", "NEW ZEALAND"]
                },
                "postcode" : {
                    "required" : false      
                }
            }
        },
        "country": {
            "type" : "string",
            "enum" : [
                // various country codes and names...
            ],
            "default" : "AUS"
        }
    }
}

推荐答案

这在草案的版本 3 中绝对是可能的.由于您有完整的允许国家/地区列表,因此您可以执行以下操作:

This is definitely possible with version 3 of the draft. Since you have a complete list of allowed countries, then you could do something like this:

{
    "type": [
        {
            "title": "New Zealand (no postcode)",
            "type": "object",
            "properties": {
                "country": {"enum": ["NZ", "NZL", "NEW ZEALAND"]}
            }
        },
        {
            "title": "Other countries (require postcode)",
            "type": "object",
            "properties": {
                "country": {"enum": [<all the other countries>]},
                "postcode": {"required": true}
            }
        }
    ],
    "properties": {
        "country": {
            "type" : "string",
            "default" : "AUS"
        },
        "postcode": {
            "type" : "string"
        }
    }
}

因此,您实际上为架构定义了两种子类型,一种用于需要邮政编码的国家/地区,另一种用于不需要邮政编码的国家/地区.

So you actually define two sub-types for your schema, one for countries that require a postcode, and one for countries that do not.

EDIT - v4 版本非常相似.只需将顶级 "type" 数组重命名为 "oneOf".

EDIT - the v4 equivalent is extremely similar. Simply rename the top-level "type" array to "oneOf".

这篇关于JSON Schema - 根据另一个字段的值指定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆