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!



12 comments:

  1. Hi there,
    Great function. The only issue I see is that it doesn't seem to work for sub-object functions.

    For example:

    {
    subObj: {
    a: 42,
    f: function(a) {
    console.log("The answer to life, the universe, and everything is " + this.a"); },
    someOtherObj: {
    x: 12
    }
    }

    Hit me back at jesse at icos dot net dot nz if im wrong!

    Cheers,
    Jesse

    ReplyDelete
    Replies
    1. Actually, it works if you fix 2 syntax errors in the example above.

      var obj = {
        subObj: {
         a: 42,
         foo: function(a) {
          console.log("The answer ... everything is " + this.a);
         },
        someOtherObj: {
          x: 12
         }
        }
      }

      function bar(){
         var str = JSONfn.stringify(obj);
         var objfn = JSONfn.parse(str);

         console.log(objfn.subObj.foo());
      }

      bar();

      Best regards,

      -Vadim

      Delete
  2. Hi Vadim,

    I am attempting to use my textarea as a live object editor and then pass this value through to JavaScript on submit and use JSONfn.stringify/parse, but unfortunately I can't seem to get it to work. Any ideas?

    James

    ReplyDelete
  3. Hi Vadim,

    only way I've found is through eval();

    eval('var x='+objToRevive)

    Any other way this could be achieved?

    ReplyDelete
  4. Hi James.

    Sorry, haven't check this blog for a while.

    JSONfn is useful only to convert javascript object with member functions to a string and convert this string back to the javascript object.
    Try following: create a simple object with a very basic function and stringify it with JSONfn. Take a look at the string. Now, if you type this string in textarea and parse it with JSONfn, you get your original object. But I think it's not what you're looking for.
    In your case "eval()" is the only way to implement the task.

    --Vadim

    ReplyDelete
  5. Hey Vadim,

    This is billiant! I was looking for something like this for a long time.

    I can't wait to test it out.

    Thanks a lot for sharing!

    Best,
    Peter

    ReplyDelete
  6. Hi Vadim,
    When I try to parse the stringified JSON object, the 'arguments' and 'caller' attributes of each function recieve a type-error : 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context. I need to get null as a value of 'caller' and 'attributes' of each function.
    Do you have anything for this ?

    ReplyDelete
  7. its really helpful and great content ..

    ReplyDelete