jsont

Simple json template language

jsont

Simple json template language

$ npm install jsont
$ component install CamShaft/jsont
  • Simple
  • Valid JSON
  • Extensible
  • Auto-parallelization of templated properties

Input:

{
  "name": "`user.firstName`",
  "birthday": "`user.birthday | date:'MMMM Do'`",
  "addresses": "`user.addresses | map | partial:address`"
}

Output:

{
  "name": "Cameron",
  "birthday": "September 19th",
  "addresses": [
    {
      "street": "123 Fake Street",
      "city": "Nowhere",
      "country": "USA"
    },
    {
      "street": "Broadway Street",
      "city": "NY",
      "country": "USA"
    }
  ]
}
var jsont = require('jsont')();
 
var template = require('./my-template.json');
 
var options = {};
 
jsont.render(template, options, function(errout) {
  console.log(out);
});

You can easily extend jsont by calling use:

var jsont = require('jsont')();
 
jsont.use('reverse', function(inputnext) {
  next(null, input.reverse());
});

In your template you can then call the helper by piping data to it:

{
  "reversed-name": "'Cameron' | reverse"
}

Out comes:

{
  "reversed-name": "noremaC"
}

You can also pass arguments and chain arguments

{
  "list": "'1,2,3,4,5' | split:',' | map | to-int"
}
jsont.use('split', function(inputseparatornext) {
  next(null, input.split(separator));
});
 
jsont.use('to-int', function(inputnext) {
  next(null, parseInt(input));
});

And we get:

{
  "list": [
    1,
    2,
    3,
    4,
    5
  ]
}

Since helpers are all asynchronous behind the scenes we get parallelization in a simple form:

var api = require('./api');
 
jsont.use('userLikes', function(idnext) {
  api.likes(id, next);
});
 
jsont.use('userFollowers', function(idnext) {
  api.followers(id, next);
});
 
jsont.use('length', function(likesnext) {
  next(null, likes ? likes.length : 0);
});
 
jsont.use('partial', function(datapartialnext) {
  // load your partial here 
  jsont.render(partial, data, next);
})
{
  "likes": "`id | userLikes | length`",
  "followers": "`id | userFollowers | map | partial:follower`"
}

Everything gets put on the event loop and renders as responses come back.

{
  "likes": 42,
  "followers": [
    {
      "id": 1,
      "name": "Scott"
    },
    {
      "id": 2,
      "name": "Dave"
    }
  ]
}
$ npm test