Login Register

High-Level Data Format Conversion

Dojo relies on JavaScript objects and arrays for most of its internal communication. Unfortunately, the world doesn't work solely in JavaScript and you must convert data formats into JavaScript before Dojo can use them. Specifically:

  • HTML Forms keep data for display and entry for the browser. Its contents live in a DOM tree.
  • URL Query Parameters are used to pass form data to a server via HTTP GET.
  • JSON is a popular XML alternative optimized for performance, and is often used where you can control the web service.

Dojo, being the diplomat that it is, can convert to and from most of these formats. Why not all? Because strictly speaking, the formats are not equivalent. JavaScript and JSON model arrays with ordered indexes, while HTML forms and URL queries model them as unordered collections. To illustrate:

Source format Comments Example
HTML Form The array b is not ordered, so we don't know if 2 or 3 appears first. Therefore, converting from an ordered array like in JavaScript loses information. Converting to JavaScript is impossible unless we make a "guess" on the ordering. Also, the heirarchy is restricted to two levels - the form "x" at the root, and all other data elements below it, with arrays adding at most one level. You cannot nest any further.
<form name="x">
   <input type="text" name="a" value="1">
   <input type="text" name="b" value="2">
   <input type="text" name="b" value="3">
</form>
URL Query Same limitations as HTML form. ?a=1&b=2&b=3
JavaScript Allows arbitrary nesting and grouping. Arrays are ordered.
var x = {a: 1, b: [2, 3] };
JSON Same limitations as JavaScript.
{"x": {"a": 1, "b": [2, 3] }}

Given those limitations, here are the dojo conversion functions. All are available in Dojo Base, so no required's are necessary.

Source format To HTML Form To URL Query To JavaScript To JSON
HTML Form N/A dojo.formToQuery() dojo.formToObject() dojo.formToJson()
URL Query None N/A dojo.queryToObject() None
JavaScript None dojo.objectToQuery() N/A dojo.toJson()
JSON None None dojo.fromJson() N/A