Converting objects into JSON string

Does saving string only limit our usage with local storage? No.

It can still save object by making the object into string. Technically we can use any kind of string serialization but JSON is a good choice here.

Here is how we can convert the data between string and object by using the JSON utility.

JSON.stringify(obj) to convert object into string. And

JSON.parse(string) to convert string into object.

Assume now we have the following code of a JavaScript data object. The last two lines convert the object into string and pares back to object again.

1var obj = {
2  name: "Thomas Mak",
3  age: 27,
4  books: ["HTML5", "Flash"],
5  languages: ["JavaScript", "ActionScript", "HTML", "CSS"],
6}
7var string = JSON.stringify(obj);
8var object = JSON.parse(string);

And this is how browser executes the code above.

Json parse result

By using the JSON stringify and parse technique, we can use local storage to store and retrieve data.

 1var obj = {
 2  name: "Thomas Mak",
 3  age: 27,
 4  books: ["HTML5", "Flash"],
 5  languages: ["JavaScript", "ActionScript", "HTML", "CSS"],
 6}
 7
 8localStorage["data"] = JSON.stringify(obj);
 9
10// getting back the data
11var data = JSON.parse( localStorage["data"] );

Borwsers offer inspector to check the stored data. And please note that the user can alter any data stored in local.

Inspect localstorage

What’s next? We’re going to take a look at “More complex keys”.

overlaied image when clicked on thumbnail

Makzan | Mobile web app dev with phonegap | Table of Content