user1566811
user1566811

Reputation:

How to make a patternProperties field in a json schema mandatory?

This should be a pretty quick yes or no, but I haven't been able to find the answer on SO or elsewhere. I want to make a set of schemas with a nice hierarchical dependency scheme rooted at an entity schema. The schema I want is

{                                                        
    "$schema": "http://json-schema.org/draft-04/schema#",
    "id": "entity",                                      
    "type": "object",                                    
    "patternProperties": {                               
       "^.+Id$": {                                 
             "type": "string"                          
        }                            
    },
    "required": [
        "^.+Id$"
    ]                                          
}    

Basically, I want every entity, for example a Person, to require a field called somethingId (for person, probably personId). However, using "required" in this way seems to force an actual field named "^.+Id$" rather than that the object must have one field matching the pattern. Is there a way to do what I want here?

Thanks in advance.

Upvotes: 0

Views: 1769

Answers (2)

esp
esp

Reputation: 7687

This can be achieved without changing data structure with this schema:

{
  "patternProperties" : {
    "^.+Id$": {                                 
      "type": "string"
    }
  },
  "minProperties": 1,
  "additionalProperties": false
}

Upvotes: 2

jruizaranguren
jruizaranguren

Reputation: 13605

As you mention in your comment, you can not enforce dynamic property keys in the required clause.

But if you can allow for a nested definition, you can model your Identifier as follows:

{
    "properties" : {
        "identifier" : {
            "additionalProperties" : false,
            "minProperties" : 1,
            "maxProperties" : 1,
            "patternProperties" : "^.+Id$ "
        }
    },
    "required": ["identifier"]
}

This way your identifier must have a unique property with a key validating your regex.

Upvotes: 0

Related Questions