Native Browser Support for JSON (Part 1 of 2)

JavaScript Object Notation, or JSON, is a text format used to represent JavaScript objects as strings.  Like other text formats, JSON is not dependent on a specific programming language.  Because of this, JSON libraries have been created for a number of popular programming languages including C/C++, Java, and PHP.  Originally, even JavaScript required libraries in order to use JSON.  In an effort to increase speed and security, modern browsers have incorporated native JSON support.  By processing JSON natively, performance overheads associated with JavaScript libraries are avoided.  Security is also improved by removing calls to eval() or untrusted libraries.

Browsers with native JSON support define a global object named “JSON”.  The “JSON” object contains two methods, parse() and stringify(), which are used to serialize and deserialize objects.  This remainder of this post is broken into two parts.  The first part covers deserialization using the parse() method, while the second part covers serialization using stringify().  This post assumes that the reader already has a working knowledge of JSON syntax.

Constructing Objects from JSON Strings

To build a JavaScript object from a JSON formatted string, the parse() method is used.  parse() is used as a safer alternative to eval(), because, while eval() will execute arbitrary JavaScript code, parse() was designed to only handle valid JSON strings.

The syntax of the parse() method is shown below.  The first argument, “text”, is a JSON formatted string.  If “text” is not a valid JSON string, a SyntaxError exception will be thrown.  If no problems are encountered, parse() returns a JavaScript object corresponding to the JSON string.  parse() also takes an optional second argument named “reviver” which I’ll cover shortly.

JSON.parse( text[, reviver] )

In the following example, the parse() method is used to construct an object from a JSON string.  The object, “obj”, has two properties, “foo” and “bar” which hold the values 10 and 20.

var string = "{\"foo\":10, \"bar\":20}";
var obj = JSON.parse(string);

// obj.foo is equal to 10
// obj.bar is equal to 20

The second argument to parse(), “reviver”, is a function that allows an object to be transformed during parsing.  As each property is parsed from the JSON string it is run through the reviver function.  The value returned by the reviver function is used as the property’s value in the constructed object.  If an undefined value is returned by the reviver function then the property is removed from the object.

The reviver function itself takes two arguments, the property name (key) and its parsed value.  The reviver should always check the key argument for the empty string.  The reason is, after the reviver is called on each individual property, it is then called on the constructed object itself.  On the last call to the reviver function, the empty string is passed as the key and the constructed object is passed as the value.  An example reviver function would look like this:

function(key, value) {
  // check for the top level object
  if (key === "")
    // be sure to return the top level object
    // otherwise the constructed object will be undefined
    return value;
  else
    // return the original untransformed value
    return value;
}

In the next example, another object is constructed from the same JSON string.  However, in this example a custom reviver function named square() is used.  As the name implies, the square() function squares the value of each property encountered during parsing.  Due to the presence of the reviver function, the values of “foo” and “bar” become 100 and 400 respectively.

var square = function(key, value) {
    if (key === "")
      return value;
    else
      return value * value;
  };
var string = "{\"foo\":10, \"bar\":20}";
var obj = JSON.parse(string, square);

// obj.foo is 100
// obj.bar is 400

Things to Remember

  • Always use native JSON handling when possible.
  • The JSON.parse() method builds a JavaScript object from a JSON string.
  • A reviver function can transform an object during parsing.
  • Always check a reviver function’s key argument for the empty string.

Continue to Part 2 of this post.


Comments are closed.