Convert objects and functions to valid JavaScript source code?

I have a JavaScript object that looks something like this:

{ bacon: [Function], hello: [Function], tables: [Function] }

Where [Function] is an actual JavaScript function.

I want to write this to a .js file with contents like:

var Templates = /*source code here*/

How can I get the source code for the object and function properties as a string, such that eval'ing this "source code string" will give me back the same object?

I rolled my own serializer:

var templates = { /* object to stringify */ };
var properties = [];
_.each(templates, function(value, key) {
    properties.push(JSON.stringify(key)+': '+value.toString());
});
var sourceCode = 'var Templates = {' + properties.join(",\n") +'};';

This gives me back:

var Templates = {"bacon": function anonymous(locals, attrs, escape, rethrow, merge) { ... },
"hello": function anonymous(locals, attrs, escape, rethrow, merge) { ... },
"tables": function anonymous(locals, attrs, escape, rethrow, merge) { ... }
};

(snipped bodies for brevity)

If I understand what you're trying to say, this would show me the function code:

myObj = {

    myMethod: function() {
        console.log("This is my function");
    }
}

console.log(myObj.myMethod.toString());

In Javascript a function is an object. The Function object supports the method toString(). This will actually give you the source code of a function. Like this:

function foo() {
    var a = 1 + 1;
}

alert(foo.toString()); // will give you the above definition

You can use JSON.stringify to accomplish this via the replacer argument:

var myObj = { a  : 1, b : function(val) { doStuff(); };

var replacer = function(key, val) {
      return "key : " + val.toString();
};

console.log(JSON.stringify(myObj, replacer));

I haven't tested this but the idea should be sound.

If you may want to use node.js, you can use a lib that can handle ASTs. You may have a look at https://github.com/substack/node-falafel