Simple automatic JSON serializer in ActionScript

Part of what I'm working on right now might involve serializing data into JSON so I'm looking into how I can efficiently serialize a data structure into JSON in ActionScript. Here's the simplest method I could find: It overrides the toString() method in the prototypes of the Array, Object and String classes (yep, good 'ol prototype-based ActionScript) to basically make a complex data structure write itself out in JSON.

// Simple JSON Serializer
// Copyright © 2007 Aral Balkan
// Released under the open source MIT license.
// http://opensource.org/licenses/mit-license.php

Object.prototype.toString = function()
{
  var str:String = "{";

  for (var i:String in this)
  {
    str += '"' + i + '": ' + this[i].toString() + ", ";
  }

  str = str.substr(0, str.length-2);
  str += "}";

  return str;
}

Array.prototype.toString = function()
{
  var str:String = "[";

  var len:Number = this.length;
  for (var i = 0; i < len; i++)
  {
    str += this[i].toString();
    if ( i != len-1 ) str += ", ";
  }

  str += "]";
  return str;
}

String.prototype.toString = function() { return '"' + this + '"'; };

To test it, simply #include the auto_json_serializer.as file and then trace out a complex data structure. (If this is too old-school for you, you can always make it into a Mixin.)

#include "auto_json_serialize.as"

data = [1, 'hello', true, [2, 3.1], {a:[{x:10, y:20}, 4], b:false}];
trace (data);

The test, above, traces [1, "hello", true, [2, 3.1], {"a": [{"x": 10, "y": 20}, 4], "b": false}]. You can verify the validity of the resulting JSON using a strict parser like simplejson or this useful little online JSON syntax checker by Colin Ramsay.

A JSON serializer in about 20 lines of code -- not bad! :)

Update: Madarco mentioned in the comments that the code above does not escape strings as it should. Adding that functionality in adds as many lines of code as the rest of it. The code I've added below to the overriden toString() method of the String class is from the ActionScript JSON class by Trannie Carter.

String.prototype.toString = function()
{
  // From JSON.as by Trannie Carter <tranniec@designvox.com>
  // http://json.org/json.as
  l = this.length;
  s = '"';
  for (i = 0; i < l; i += 1)
  {
    c = this.charAt(i);
    if (c >= ' ')
    {
      if (c == '\\' || c == '"')
      {
        s += '\\';
      }
      s += c;
    }
    else
    {
      switch (c)
      {
        case '\b':
          s += '\\b';
          break;

        case '\f':
          s += '\\f';
          break;

        case '\n':
          s += '\\n';
          break;

        case '\r':
          s += '\\r';
          break;

        case '\t':
          s += '\\t';
          break;

        default:
          c = c.charCodeAt();
          s += '\\u00' + Math.floor(c / 16).toString(16) +
              (c % 16).toString(16);
      }
    }
  }

    s += '"';

  return s;
}

Download version 0.2 here (6kb, MD5: 2243b3b2d0a5ae2570511de6f47c7a35).

Comments