Dmitry K
Dmitry K

Reputation: 184

jsonSchema validating numerical keys by pattern

Could you help me, how I can validate "keys"(ex. "1","2","3") of list items in following json:

   {
    "list" : {
        "1" : {
            "element1" : "1",
            "element2" : "2"
        },
        "2" : {
            "element1" : "1",
            "element2" : "2"
        },
        ....
        "512" : {
            "element1" : "1",
            "element2" : "2"
        }
    }
   }

Please give me common examples to validate keys in json, too.

Upvotes: 2

Views: 4312

Answers (1)

Jason Desrosiers
Jason Desrosiers

Reputation: 24489

JSON Schema has three ways to constraint the property names of an object.

properties

The properties keyword allows you to set an exact match for property names.

{
  "type": "object",
  "properties": {
    "1": { ... },
    "2": { ... },
    ...
  }
}

patternProperties

The patternProperties keyword constrains any property name that matches a regular expression to validate against a given schema.

{
  "type": "object",
  "patternProperties": {
    "[1-9][0-9]*": { ... }
  }
}

propertyNames

The propertyNames keyword constraints property names to match the given schema.

{
  "type": "object",
  "propertyNames": {
    "pattern": "[1-9][0-9]*"
  }
}

Edit 12-19-2018 Improve answer, add missing patternProperties, add new (since original answer) option propertyNames.

Upvotes: 5

Related Questions