Mark Nottingham

Schema for JSON

Thursday, 30 November 2006

HTTP APIs

One of the perceived deficiencies of JSON is that it doesn’t have a schema language. I say “perceived” because the problems that a schema language brings often outweigh the benefits; after all, look at the mess that XML Schema is in.

Even that said, schemas are useful for documentation and QA. So, I’m finding the work that Robert Cerny has done very interesting; it’s basically schemas for JSON, in JSON (or very nearly so). For example, here’s the schema for the cerny doc format;

CERNY.require("CERNY.js.doc.Schema",
              "CERNY.text.DateFormat",
              "CERNY.schema");

arrayOf = CERNY.schema.arrayOf;
optional = CERNY.schema.optional;
nonEmptyString = CERNY.schema.nonEmptyString;
isoDate = CERNY.schema.isoDate;

CERNY.js.doc.Parameter = {
    name: nonEmptyString,
    documentation: nonEmptyString
};

CERNY.js.doc.Function = {
    name: nonEmptyString,
    documentation: arrayOf(nonEmptyString),
    parameters: arrayOf(CERNY.js.doc.Parameter),
    returnValue: optional(nonEmptyString)
};

CERNY.js.doc.HistoryEntry = {
    date: isoDate,
    entry: nonEmptyString
};

CERNY.js.doc.Script = {
    name: nonEmptyString,
    author: nonEmptyString,
    creationDate: isoDate,
    modificationDate: optional(isoDate),
    documentation: arrayOf(nonEmptyString),
    history: arrayOf(CERNY.js.doc.HistoryEntry),
    functions: arrayOf(CERNY.js.doc.Function),
    uses: arrayOf(nonEmptyString)
};

Pretty easy. The big questions are whether it hits the 80/20 point (at first glance, I think it might, but I haven’t played with it yet), and whether it avoids the versioning nightmare that trapped XML Schema (again, looks good so far, but it’s early days).

Also, CERNY.require’s relationship to URIs is very, very interesting…