Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
642 views
in Technique[技术] by (71.8m points)

jsonschema - How to define choice element in json schema when elements are optional?

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

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

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"
}

or

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

or

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...