Native JSON Parsing in Dojo

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 json.org’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:

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.

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.