What is the proper way to serialize / deserialize objects?

treycarroll
Giga Guru

I would dearly love to avoid reinventing the wheel here, but though this code does not throw errors, neither does it actually work:

 

var x = JSON.stringify({Texas:'Austin',Michigan:'Lansing'});
var y = JSON.parse(x);
gs.log(y.Texas);//prints undefined instead of Austin

 

So instead I am doing this:

 

//Accepts a string representation of an object: "{prop1:'aaa',prop2:'bbb'}"
//Returns an object with the specified properties
function toObject(stringifiedObject) {
       if (typeof stringifiedObject !== 'string') {
               throw "Parameter error. toObject() only accepts a string.";
       }
       var guts = stringifiedObject.match(/^\{([^\}]*)\}$/);
       var properties = guts[1].split(',');
       var obj = {};
       for (var i = 0; i < properties.length; i++) {
               var prop = properties[i].trim().split(':');
               obj[prop[0].trim()] = prop[1].trim().replaceAll('\'','').replaceAll('"','');
       }
       return obj;
}

//Accepts an object and returns a string similar to a stringified JSON object
//ignores function type properties
function stringify(obj) {
       var str = '{';
       for (var k in obj) {
               if (typeof this[k] != 'function') {
                       str += k + ':\'' + obj[k] + '\',';
               }
       }
       str = str.substring(0, str.length - 1);//remove the unneeded comma
       str += '}';
       return str;
}

gs.log(toObject(stringify({ Texas: 'Austin', Michigan: 'Lansing' })).Texas);//correctly outputs Austin

 

Yes, it's crude and only supports one level of properties.     What is a better way?       Even if I could find helpful library with similar functionality (like underscore js), where do you add such scripts so that they'll be available in BRs and Inbound Email Actions?     I learned the hard way that adding them in UI Scripts and making them global will bring down your instance!

 

Your advice would be greatly appreciated.

 

Thanks,

 

Trey Carroll

1 ACCEPTED SOLUTION

Hi Trey,



There's a Script Include called JSON which has some methods to encode and decode JSON server side. The following should work for you:



var j = new JSON()


var x = j.encode({Texas: 'Austin', Michigan: 'Lansing'});


var y = j.decode(x);


gs.log(y.Texas);


View solution in original post

4 REPLIES 4

treycarroll
Giga Guru

By the way, the reason that I'm doing this is that I'm finding that Email Notifications seem to only allow passing of strings into Parm1 and Parm2.     Thus, I have to re-hydrate my objects once I get event.ParmN in the mail_script.



If there is a better way to get a live object into a mail script I would love to know to do it without going to this trouble.



BTW, there was a typo in my code:


this[k] //should have been obj[k]


My final version of the code looked like this:



var u_GmfObjectSerializer = Class.create();


u_GmfObjectSerializer.prototype = {


      initialize: function () {


      },



      //Accepts a string representation of an object: "{prop1:'aaa',prop2:'bbb'}"


      //Returns an object with the specified properties


      //Replaces new lines with <br/> if the 2nd param is true


      parseToObject: function (stringifiedObject, replaceNewlineWithBr) {


              if (typeof stringifiedObject !== 'string') {


                      throw "Parameter error. toObject() only accepts a string.";


              }



              var matchBtwBraces = stringifiedObject.match(/^\{([^\}]*)\}$/);


              if (matchBtwBraces != undefined && matchBtwBraces.length == 2) {


                      var obj = {};


                      var m;


                      while (m = /([^:]+):['"]([^'"]*)['"],?/g.exec(matchBtwBraces[1])) {


                              var key = m[1];


                              var val = m[2];


                              obj[key] = (replaceNewlineWithBr) ? val.replace(/(?:\r\n|\r|\n)/g, '<br/>') : val;


                      }


              } else {


                      throw "Parameter error. String was found to be improperly formated.   Must start and end with a curly brace.";


              }


              return obj;


      },



      //Accepts an object and returns a string similar to a stringified JSON object


      //ignores function type properties


      stringify: function (obj) {


              var str = '{';


              for (var k in obj) {


                      if (typeof obj[k] != 'function') {


                              str += k + ':\'' + obj[k] + '\',';


                      }


              }


              str = str.substring(0, str.length - 1);//remove the unneeded comma


              str += '}';


              return str;


      },


      type: 'u_GmfObjectSerializer'


}


Hi Trey,



There's a Script Include called JSON which has some methods to encode and decode JSON server side. The following should work for you:



var j = new JSON()


var x = j.encode({Texas: 'Austin', Michigan: 'Lansing'});


var y = j.decode(x);


gs.log(y.Texas);


Just wanted to add that the syntax editor will throw a warning if you do it this way...which, nevertheless, works