0

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}}
            }
        }
    }
}   
museshad
  • 498
  • 1
  • 8
  • 18

2 Answers2

0

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.

Relequestual
  • 11,631
  • 6
  • 47
  • 83
  • @Relequestual- Thanks for your comment. I think the country code is fine and does not need to be validated by the schema. I'm looking at how to validate that there are exactly 5 elements in the list – museshad Aug 04 '22 at 15:12
  • If you don't care about that, you can use `additionalProperties` which will apply to all properties. – Relequestual Aug 04 '22 at 15:13
  • 1
    What @Relequestual is saying is that the regular expression in `patternProperties` applies to the _property name_. "US" is not a match for `^[0-9]+$`. You need to change that to `^[A-Z]{2}$` to match a country code. – gregsdennis Aug 04 '22 at 21:00
0

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

  "$minProperties": 5,
  "$maxProperties": 5
Jason Desrosiers
  • 22,479
  • 5
  • 47
  • 53