HTML and CSS Reference
In-Depth Information
Generally, the problem here is that by choosing a custom serialization format you make yourself
responsible for writing both the serializer and the deserializer. In addition, every format requires a
distinct ad hoc pair of serializer and deserializer.
In JavaScript, a better option does exist; it entails using a special notation known as the JSON
format. The acronym JSON stands for JavaScript Object Notation.
The JSON format
JSON is a text format easy to handle and read for both humans and software. Basically, JSON defines
a set of conventions through which any object can have its data serialized to a standard format. A
JSON string is made of a collection of name/value pairs each of which identifies a property name and
its value. A special convention also exists for rendering arrays. The following text shows the JSON
version of a Task object filled with default values:
"description":"This is my new task",
"status":"Not Started",
The great news is that JavaScript and Windows 8 provide native tools to create a JSON string from
a JavaScript object and to obtain a JavaScript object from a JSON string. In addition, the generality
of the JSON format makes it suitable to treat just about any object. This means that you need only
one pair of serializer and deserializer in your code, regardless of the number of objects you intend to
persist and also regardless of their structure.
Serializing the Task object to JSON
To use JSON in the TodoList application, all you need to do is use the following code for the TodoList.
serializeTask function:
TodoList.serializeTask = function (task) {
return JSON.stringify(task);
JSON.stringify is a JavaScript native function that turns any JavaScript object into a JSON
compatible string. Figure 10-4 shows the JSON content of a Task object being read with a plain text
editor, such as Notepad.
Search WWH ::

Custom Search