当元素是可选的时,如何在json模式中定义选择元素? [英] How to define choice element in json schema when elements are optional?

查看:228
本文介绍了当元素是可选的时,如何在json模式中定义选择元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

------------ Josn模式-----------

------------Josn schema-----------

{
    "type": "object",
    "properties": {
        "street_address": {
            "type": "string"
        },
        "city": {
            "type": "string"
        },
        "state": {
            "type": "string"
        }
    },
    "required": [
        "street_address"
    ],
    "additionalProperties": false
}

在上面的模式中,我想在城市和州之间进行选择.可以在json中输入城市或州名.这样json以下将是无效

In above schema i want to create a choice between city and state. That is either city or state can come in json. So that below json would be invalid

{
    "street_address": "abc",
    "city": "anv",
    "state": "opi"
}

下面的一个应该是有效的

and below one should be valid one

{
    "street_address": "abc"
}

{
    "street_address": "abc",
    "city": "anv"
}

{
    "street_address": "abc",
    "state": "opi"
}

请问有人可以帮我修改上述架构以实现目标.

Can some one please help me to modify above schema to accomplish the goal.

推荐答案

当只有一个替代方案应持有时使用"oneOf",而至少应具有一种替代方案时则使用"anyOf".

Use "oneOf" when only one of the alternatives should hold, and "anyOf" when at least one of the alternatives should hold.

您无需在oneOf中重复公共属性.完成目标的最短方法是:

You don't need to repeat common properties within oneOf. The shortest way to accomplish your goal would be:

{
    "type" : "object",
    "properties" : {
        "street_address" : {
            "type" : "string"
        },
        "city" : {
            "type" : "string"
        },
        "state" : {
            "type" : "string"
        }
    },
    "oneOf" : [{
            "required" : ["city"]
        }, {
            "required" : ["state"]
        }
    ],
    "required" : [
        "street_address"
    ],
    "additionalProperties" : false
}

这篇关于当元素是可选的时,如何在json模式中定义选择元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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