case
ADM Blog
28Apr/100

Serialize JavaScript object to JSON

Recently, on a project I was working, I needed a function to serialize a JavaScript object and all I could find online were scripts and jquery plugins for serializing a html form. Then, I found this, a script that takes advantage of the .toSource() method available in Gecko-based browsers and for the rest of them plain old recursion. But it does the trick as expected and I'm pretty sure someone else might need it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function serialize(_obj) {
   if (_obj != undefined && typeof _obj.toSource !== 'undefined' && typeof _obj.callee === 'undefined') {
      return _obj.toSource();
   }
   switch (typeof _obj) {
      case 'number':
      case 'boolean':
      case 'function':
         return _obj;
         break;
      case 'string':
          return '"' + _obj.replace(/"/mg, "'") + '"';
          break;
      case 'object':
          var str;
          if (_obj.constructor === Array || typeof _obj.callee !== 'undefined') {
              str = '[';
              var i, len = _obj.length;
              for (i = 0; i < len-1; i++) { str += Utils.serialize(_obj[i]) + ','; }
              str += Utils.serialize(_obj[i]) + ']';
          } else {
              str = '{';
              var key;
              for (key in _obj) { str += key + ':' + Utils.serialize(_obj[key]) + ','; }
              str = str.replace(/\,$/, '') + '}';
          }
          return str;
          break;
      default:
          return '""';
          break;
      }
}

To deserialize it, just use eval().

Also, if you need the same thing for your Flash/Flex Actionscript3 project, here is a class for that as well -> Click Me.

Cheers!

Comments (0) Trackbacks (0)

Reply

( Cancel )

CommentLuv badge

*

No trackbacks yet.