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

后端 未结 4 1899
深忆病人
深忆病人 2020-12-20 15:00

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

{
    \"type\": \"object\",
    \"properties\": {
        \"street_address\": {
            \"type\": \"string\"
        }         


        
4条回答
  •  被撕碎了的回忆
    2020-12-20 15:32

    You would need to use "oneOf". Like so:

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

    You'll notice, it's a bit repetitive. Since, in your example, you only provide a "type" for each property, the repetition is not so bad. But if you have more complex properties, you could consider using deifinitions to define each property only once, at the top and then using $ref to reference the definition. Here's a good article on that.

提交回复
热议问题