Skip to content

Instantly share code, notes, and snippets.

@anvaka
Created October 1, 2012 23:59
Show Gist options
  • Star 26 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save anvaka/3815296 to your computer and use it in GitHub Desktop.
Save anvaka/3815296 to your computer and use it in GitHub Desktop.
JavaScript Function Serialization
function functionReplacer(key, value) {
if (typeof(value) === 'function') {
return value.toString();
}
return value;
}
function functionReviver(key, value) {
if (key === "") return value;
if (typeof value === 'string') {
var rfunc = /function[^\(]*\(([^\)]*)\)[^\{]*{([^\}]*)\}/,
match = value.match(rfunc);
if (match) {
var args = match[1].split(',').map(function(arg) { return arg.replace(/\s+/, ''); });
return new Function(args, match[2]);
}
}
return value;
}
var person = {
name : 'John Smith',
age : 42,
isJohn: function() {
return !!this.name.match(/John/);
}
};
jsonString = JSON.stringify(person, functionReplacer);
restoredPerson = JSON.parse(jsonString, functionReviver);
console.log(restoredPerson.isJohn());
@alexbeletsky
Copy link

That's definitely cool, man :)

@anvaka
Copy link
Author

anvaka commented Nov 15, 2012

Thank you, dude!

@AlanTai
Copy link

AlanTai commented Aug 7, 2013

awesome!

@aamirsaeed
Copy link

hi anvaka. I see your code quite interesting. can you have the advance version i.e it can be used for closures also.

@umairshahid436
Copy link

Hi
anyone who know how we can convert javascript function into json object
suppose this is a function

app.controller('myctrl',function($scope){

    var rec=function rec(){                                     
        var rect = new joint.shapes.basic.Rect({
        position: { x:x1 , y: y1 },
        size: { width: 100, height: 30 },
        attrs: { rect: { fill: 'red' }, text: { text: 'box' + i, fill: 'white' } }
        });
        i=i+1;
        x1=x1+120;
        graph.addCells([rect]); 



    }

}

i want to convert into json object
anyone who know plz help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment