bigmlcom/closchema — pull request #5 by charleslparker (2012-01-20 01:03:18+00:00)
Title: Union Typing and Referencing - Just In Time for New Schema Design!

Adding support in closchema for union typing and referencing. Union typing has been done strictly by the spec (as far as I can tell). I didn't want to implement the whole JSON hyper-schema for referencing, so I've instead opted for the simple version used in the Dojo 1.2 validator by Kris Zyp.

## Union Typing

Here's a reference that explains it pretty well:

http://groups.google.com/group/json-schema/browse_thread/thread/36839435ddb65457/3126adcb898181cc

Basically, anywhere you define a `:type`, it can now be a vector. In this vector, you can have multiple types. If any of these validate, the JSON is valid.

The types may be primitive or entire JSON schemas. So this is fine:

```
"type" : ["integer" "string"]
```

and so is this:

```
"type" : [
"integer"
{
"type" : "object"
"properties" : {
"id" {"type" : "integer"}
"name" {"type" : "string"}}
}]
```

This is really nice in combination with the `additionalProperties` JSON keyword, which lets you specify a type for all unspecified keys in a map (I think?). Now, if you have a map, and you're not sure what the keys will be, but you know what type(s) the values will be, you can validate them anyway.

## Referencing

Basically implement the **file-based** part of referencing described here (at the end of the post):

http://www.sitepen.com/blog/2008/10/31/json-schema/

Let me say that again: **I haven't implemented ID based referencing**, so that doesn't work.

The idea is that in place of a schema for any property you can put a reference to a file containing a schema using the key `$ref` when describing a property:

```
{
"type" : object
"properties" : {
"id" : {"type" : "integer"}
"address" : {"$ref" : "path/to/file"}
}
}
```
Reading is lazy, so the schema is read until we hit it at validation time. Files are read using `slurp` and `clojure.data.json`. I also do a stupid little cache so that files aren't read over and over again (when validating arrays, for example).

Also, I didn't open up a new branch for this pull request, so it's just on master (in my own fork, of course). Oops. Hope it isn't a problem in any way.