Tuesday, August 21, 2012

Convert Javascript Object with Functions to String and String to Object

A lot of javascript developers want to serialize object and save it on server or local storage, in order to take this string later and convert it back into an object. It's not a big deal if your object has only member variables. You simply use javascript native JSON object to serialize/parse  your custom object.
But it doesn't work if your object has member function. Native JSON ignores functions. Recently I made a brief search and wasn't able to find acceptable way to manage this problem. So, I spent some time on development a very small plugin, which can help many developers to create simple and elegant applications. All plugin is just 20 lines of code, so I show it right here

----------------------------------------------------------------------------
var JSONfn;
if (!JSONfn) {
    JSONfn = {};
}
(function () {
JSONfn.stringify = function(obj) {
return JSON.stringify(obj,function(key, value){
return (typeof value === 'function' ) ? value.toString() : value;
});
}
JSONfn.parse = function(str) {
return JSON.parse(str,function(key, value){
if(typeof value != 'string') return value;
return ( value.substring(0,8) == 'function') ? eval('('+value+')') : value;
});
}
}());
------------------------------------------------------------------------------------------


       var str = JSONfn.stringify(obj);
var obj = JSONfn.parse(str);

See live demo at http://www.eslinstructor.net/jsonfn/

Enjoy!