Nerd wannabe

lazy weblog

Posts Tagged ‘json

Auto-validating JSON with optional documentation

leave a comment »

The idea is to have one of the nodes documenting the structure of the rest of them and to have the ability to write textual documentation for the values.

The node "schema?" is used to introduce this structure as a top-level node. The contents of the schema have keys in the form "key? The documentation is here", where the ? sign plays the role of a separator but also says something about the requirement for a key or value’s presence.

  • key! => key must be present
  • key? => key is optional
  • key+ => value must be non-null, and in the case of arrays it must have a length>0
  • key* => value may be null

"key", "key!" and "key+" are shorthand for "key!+",
"key?" and "key*" are shorthand for "key?*",

Any value is accepted and documents the type of the value: "", 0, 0.0, true, [], {} etc.

  • "" => any string
  • integer value = 0, value > 0 or value < 0 => integer number, positive only, negative only
  • double value = 0.0, value > 0.0 or value < 0.0 => double number, positive only, negative only
  • boolean value = true or false => boolean
  • array value = [], array value = [value1, value2..] => any array, or array containing elements in the form of either value1 or value2 (nested specification)
  • object value = {}, object value = { "key" : value, ... } => any object, or object with given schema (nested specification)

No constraints can be set on the order of elements.

Example:

{
  "schema?": {
    "title! This is shown in the window's titlebar" : "", 
    "count! The number of things" : 1, 
    "price! The price in USD" : 1.0,
    "head? Optional tag with metadata" : {
      "script? One or more script elements" : [{
        "source! Each one with a source string" : ""
      }], 
      "meta!  Array of metadata strings with at least one element" : [""], 
      "style!* Any array, even empty one"  : [], 
      "what?  Optional, any array"  : []  
    },
    "body! Main content" : {
      "div? Any number of divs": [],
      "span?": []
    }
  },

  "count" : 5,
  "title" : "JSON",
  "price" : 4.5,
  "head" : {
    "meta" : ["data"],
    "style" : [],
    "script" : [{ 
        "source" : "http://...js"
      }, { 
        "source" : "spdy://...dart", 
        "type" : "text/dart" 
      }]
  },
  "body": {
    "div" : []
  }
}

 

This also has the advantage of being valid JSON, after all. It can be a separate document used to validate objects passed over the wire, or included inline in e.g. a configuration file. And even if a JSON parser is not validating against the "schema?" the rest of the data is still usable.

Plus, you get comments in configuration files (because JSON does not allow comments..).

Written by vlad

July 4, 2014 at 8:03 am

Posted in ideas

Tagged with , ,