How to make a "patternProperty" required in JSON Schema (Ruby)

25.7k views Asked by At

Consider the following JSON :

 {
      "1234abcd" : {
                     "model" : "civic"
                      "made" : "toyota"
                      "year" : "2014"
                     }

 }

consider another JSON :

 {
      "efgh56789" : {
                     "model" : "civic"
                      "made" : "toyota"
                      "year" : "2014"
                     }

 }

the outermost alphanumeric key will vary and required, if the key was fixed; let's say "identifier" then the schema was straightforward, however since the key-name is variable, we have to use patternProperties, how can I come up with a schema that captures these requirement for the outermost key:

  1. property name (key) is variable
  2. required
  3. alphanumeric lowercase

using json-schema : https://github.com/ruby-json-schema/json-schema in ruby.

2

There are 2 answers

5
jruizaranguren On BEST ANSWER

You may have to change the regular expression to fit your valid keys:

{
"patternProperties": {
    "^[a-zA-Z0-9]*$":{
        "properties": {
              "model":{"type":"string"},
              "made":{"type":"string"},
              "year":{"type":"string"}
         }
    }
},
"additionalProperties":false
}
2
Jason Desrosiers On

The best you can do to require properties when those properties are variable is to use minProperties and maxProperties. If you want to say there must be one and only one of these alphanumeric keys in your object, you can use the following schema. If you want to say there has to be at least one, you could just leave out maxProperties.

{
  "type": "object",
  "patternProperties": {
    "^[a-z0-9]+$": {
      "type": "object",
      "properties": {
        "model": { "type": "string" },
        "make": { "type": "string" },
        "year": { "type": "string" }
      },
      "required": ["model", "make", "year"]
    }
  },
  "additionalProperties": false,
  "maxProperties": 1,
  "minProperties": 1
}