Home > Software engineering >  JSON schema requiring patternProperties
JSON schema requiring patternProperties

Time:08-05

I'm looking for help in defining the JSON schema which would validate the below sample JSON. I don't know the country codes before hand, so they can be any country code actually. In other words, I cannot use "US" or "IN" directly in the schema. Each country code must have exactly 5 values in the list

{
    "id": 1,
    "country_metric": {
        "US": [1,2,3,4,5],
        "IN": [9,0,1,4,5],
        "AU": [7,7,7,7,7]
    }
}

I realize I must use patternProperties, but cannot figure out exactly. Any help is very appreciated.

I was trying something like this, but it does not seem to work-

{
    "definitions": {},
    "$schema": "http://json-schema.org/draft-07/schema#", 
    "$id": "https://example.com/object1659608644.json", 
    "title": "Root", 
    "type": "object",
    "required": ["id", "country_metric"],
    "properties": {
        "id": {"type": "integer"},
        "country_metric": {
            "type": "object",
            "patternProperties": {
                "^[0-9] $": {"type": ["array"], "items": {"type": "integer", "minItems": 5, "maxItems": 5}}
            }
        }
    }
}   

CodePudding user response:

The key of a patternProperties object is a Regular Expression. You must define the Regular Expression you want there to allow for two capital letters.

Alternativly, you could use propertyNames with an enum of all the allowed values.

CodePudding user response:

You can use minProperities and maxProperties to constrain how many properties are in your objects.

  "$minProperties": 5,
  "$maxProperties": 5
  • Related