Create Javascript objects from a template Create Javascript objects from a template json json

Create Javascript objects from a template


So I've managed to solve this by (ab)using functions as metadata to mark the values that should be replaced in the template. This is made possible by two things:

  1. I only need valid JSON values, so I can safely say that functions aren't literal user input
  2. JSON.stringify has a replacer parameter which will traverse the object and can be used to pass the input data to the template

Using a template generator like this

var templateMaker = function (object) {    return function (context) {        var replacer = function (key, val) {            if (typeof val === 'function') {                return context[val()]            }            return val;        }        return JSON.parse(JSON.stringify(obj, replacer))    }}

I create a template object, replacing field names with functions that return the field name

var obj = {    name: "Alfred",    stats: {        age: 32,        position: {            title: function () { return 'title' },            level: function () { return 'level' }        }    }}

then I create the template function, define my input, and render it to an object

var template = templateMaker(obj);var data = {    title: "Manager",    level: 10}var rendered = template(data);

and magically, the object output looks like

{ "name": "Alfred", "stats": { "age": 32, "position": { "title": "Manager", "level": 10 } }}


Maybe template engines like Mustache would help you with this.

You can define your object template in string:

var template = '{ title: {{title}} }';

then render it with the data, and convert it to json:

var data = {title: 'I am title'};var obj = JSON.parse(Mustache.render(template, data));

UPDATE:

I read your updated example, here is the corresponding example:

var template = JSON.stringify({    name: "Alfred",    stats: {        age: 32,        position: {            level: 10,            title: '{{title}}'        }    }});var data = {title: 'I am title'};var obj = JSON.parse(Mustache.render(template, data));obj.stats.position.title == "I am title";