Reusing regular expressions in a json schema

882 views
Skip to first unread message

robert...@gmail.com

unread,
Jul 28, 2014, 8:09:08 AM7/28/14
to json-...@googlegroups.com
Hi,

Was wondering if there was a way to reuse regular expressions across a JSON schema.  

For example if I have a schema which defined the following types:

 "name": {
   
"type": "string",
   
"pattern": "^([a-z|A-Z|0-9])+$"
 
}

Which allows me to define names that like "Cat1", "Dog2", "Fred"

"namespace": {
  "type": "string",
  "pattern": "^([a-z|0-9])+(\\.([a-z|0-9])+)*$"
},

Which allow me to define namespaces that look like this: "com.animal", "com.person"

"fully-qualified-name": {
  "type": "string",
  "pattern": "^(([a-z|0-9])+\\.)*([a-z|A-Z|0-9])+$"
},

Which is really a combination of the two regexps from name and namespace and allows me to define fully qualified names that look like this: "com.animal.Cat1", "com.animal.Dog2" and "com.person.Fred"

"things": {
  "type": "object",
    "patternProperties": {"^([a-z|0-9])+(\\.([a-z|0-9])+)*$" : {}},
  "additionalProperties": false
},

Which copies the regexp for namespace and allows be to define objects that look like this:

{
  "com.animal": "Dog",
  "com.person": "Fred"
}

Is there a way I can structure the schema so I can reuse the regexps for name and namespace in fully-qualified-name and things schemas? 

Any help would be greatly appreciated.

Regards
Rob









robert...@gmail.com

unread,
Aug 6, 2014, 7:00:32 AM8/6/14
to json-...@googlegroups.com, robert...@gmail.com
Anybody?

Christopher J. White

unread,
Aug 6, 2014, 10:30:07 AM8/6/14
to json-...@googlegroups.com
Hey Rob,

If you want to build a new regex from 2 or more other regex strings, I don't see a way to do that -- it seems beyond the scope of JSON schema at this point.

As for reusing existing regex patterns, you could conceivably use $ref for this:

{
   "patterns": {
        # Just a dictionary of interesting patterns
        "name": "^([a-z|A-Z|0-9])+$",
        "namespace": "^([a-z|0-9])+(\\.([a-z|0-9])+)*$"

    }
    "things": {
        "type": "object",
        "patternProperties": {
            { "$ref": "#/patterns/namespace" } : { "$ref": "#/patterns/name" }
        }
    }
}

...cj
--
You received this message because you are subscribed to the Google Groups "JSON Schema" group.
To unsubscribe from this group and stop receiving emails from it, send an email to json-schema...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

robert...@gmail.com

unread,
Aug 6, 2014, 11:29:44 PM8/6/14
to json-...@googlegroups.com, chris...@grierwhite.com
Oh cool, I didn't know you could do that.

I'll give it a shot tonight.

Thanks

Rob
Reply all
Reply to author
Forward
0 new messages