Native JSON Parsing in Dojo

By on January 5, 2012 8:05 am

Dojo 1.7 introduces a new JSON module available at dojo/json. This differs from the legacy dojo.fromJson and dojo.toJson in that it is based on the new native JSON API in the JavaScript language (introduced in EcmaScript 5). It also delegates to the native JSON parser and serializer when they are available, providing the fastest possible execution for any given browser.

Using the new API is very easy, and should be familiar if you have used’s library or the browser native library. We get the JSON object from the “dojo/json” module and then can use the parse and stringify methods. For example, to parse JSON:

define(["dojo/json"], function(JSON){
  var jsonStr = '{"name": "value"}';
  var object = JSON.parse(jsonStr); -> "value";

Again, note that this will use the native parsing facilities of the browser/platform if they are available, otherwise they will use the library implementation.

To reverse the process and serialize an object to JSON:

define(["dojo/json"], function(JSON){
  var object = {"name": "value"};
  var jsonStr = JSON.stringify(object);
  jsonStr -> '{"name": "value"}'

Date Serialization

The new JSON module now properly serializes dates. While previously, dojo.fromJson incorrectly serialized dates as “{}”, serialization now conforms to native date serialization. Dates are serialized to the standard ISO format in UTC.

JSON.stringify({now:new Date()}) -> "{"now":"2011-06-13T19:02:19.650Z"}"

Native Performance

Staying Light

The new JSON module uses has() branching to determine whether or not to use the native JSON capability or not. This is not only a solid feature-detection based approach, but it means when you leverage browser-specific builds, the module is only a few bytes for modern browsers, particularly valuable for mobile applications.

The legacy dojo.fromJson and dojo.toJson will still be available in Dojo base, but it is recommended that you use parse and stringify functions from dojo/json now for better performance and standards conformance.