TAGS :Viewed: 9 - Published at: a few seconds ago

[ json schema issue on required property ]

I need to write the JSON Schema based on the specification defined by http://json-schema.org/. But I'm struggling for the required/mandatory property validation. Below is the JSON schema that I have written where all the 3 properties are mandatory but In my case either one should be mandatory. How to do this?.

{
    "id": "http://example.com/searchShops-schema#",
    "$schema": "http://json-schema.org/draft-04/schema#",
    "title": "searchShops Service",
    "description": "",
    "type": "object",
    "properties": {     
            "city":{
                "type": "string"                
            },  
            "address":{
                "type": "string"                
            },      
            "zipCode":{
                "type": "integer"
            }                   
    },
    "required": ["city", "address", "zipCode"]
}

Answer 1


If your goal is to tell that "I want at least one member to exist" then use minProperties:

{
    "type": "object",
    "etc": "etc",
    "minProperties": 1
}

Note also that you can use "dependencies" to great effect if you also want additional constraints to exist when this or that member is present.

Answer 2


{
  ...
  "anyOf": [
    { "required": ["city"] },
    { "required": ["address"] },
    { "required": ["zipcode"] },
  ]
}

Or use "oneOf" if exactly one property should be present