From Spherical
Jump to: navigation, search

JSON, which stands for JavaScript Object Notation, is more compact, less-process intensive alternative to XML. It's a way to store complex data objects and restore them back to their original state, similar to PHP's or Java's serialization. What does this mean to Sphere? JSON can be used to save monster stats or complex event states in a way that which doesn't involve creating custom routines to save various attributes to a comma-delimited file. The current version of the JavaScript-based JSON parser is named json2.js and while it retains the original API it boasts significant improvements in speed and efficiency.

What json2.js does is it installs additional methods to the JavaScript primitive types such as Object and Number which allow any object to be rendered down into a JSON string or vice-versa.


JSON parsing is built into ECMAScript since 2007 but for JS engines that don't natively support it you can get a script from, specifically here.


Including json2.js in your game will provide a global "JSON" object with two static methods.

  • JSON.stringify(value[, replacer, space]) - Converts value into a JSON string. replacer and space are optional: they handle how objects without a toJSON() method are dealt with, and how the text is indented, respectively. See the file itself for details.
  • JSON.parse(text[, reviver]) - Converts the JSON string text back into a JavaScript object. The optional reviver parameter is a function that can transform, replace or remove each key-value pair as it is encountered. See the file itself for details.


function Monster()
   this.fight = function ( who )
      //do some fighting
   this.magic = function ( who )
   this.loadStats( str )
      // take the json string, create an object and apply it to myself
      json = JSON.parse(str);
      for (prop in json)
         this[prop] = json[prop];
// create an instance of a monster
var slime = new Monster();
slime.hp = 10; = 2;
slime.str = 2;
slime.magic = ['Hurt','Heal','Heal More'];
slime.exp = 3; = "Green Slime";
// save the stats of the slime
jsonslime = slime.toJSONString();
jsonslime = JSON.stringify(slime);
// kill it
delete slime;
// resurrect it
var slime = new Monster();
// I'm back!