Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created September 19, 2012 13:45
Show Gist options
  • Select an option

  • Save cowboy/3749767 to your computer and use it in GitHub Desktop.

Select an option

Save cowboy/3749767 to your computer and use it in GitHub Desktop.

Revisions

  1. cowboy created this gist Sep 19, 2012.
    15 changes: 15 additions & 0 deletions stringify.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    var stringify = function(obj, prop) {
    var placeholder = '____PLACEHOLDER____';
    var fns = [];
    var json = JSON.stringify(obj, function(key, value) {
    if (typeof value === 'function') {
    fns.push(value);
    return placeholder;
    }
    return value;
    }, 2);
    json = json.replace(new RegExp('"' + placeholder + '"', 'g'), function(_) {
    return fns.shift();
    });
    return 'this["' + prop + '"] = ' + json + ';';
    };
    17 changes: 17 additions & 0 deletions usage.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    var foo = {
    a: function() { return 'a'; },
    b: function() { return 'b'; },
    'bar.baz': {
    'omg ponies!!': function() { return 'c'; }
    }
    };

    console.log(stringify(foo, 'foo'));

    // this["foo"] = {
    // "a": function () { return 'a'; },
    // "b": function () { return 'b'; },
    // "bar.baz": {
    // "omg ponies!!": function () { return 'c'; }
    // }
    // };