Thursday, March 12

How to store JSON in sessionStorage

Let's say you want to store JSON as a sessionStorage in your browser.

JSON example

[
    {
        "id": "1",
        "name": "John Doe"
    },
    {
        "id": "2",
        "name": "Jane Doe"
    },
    {
        "id": "3",
        "name": "Mike Doe"
    },
    {
        "id": "4",
        "name": "Henry Doe"
    }
]


A short Algorithm
1) Check if a browser supports sessionStorage
2) If Yes, Look for an existing data in SessionStorage
3) If No, get data from Server and then Store in SessionStorage

If(typeof(Storage) !== “undefined”){
 
 If(sessionStorage.getItem(“getUserRecords”){
  alluserRecords = JSON.parse(sessionStorage.getItem(“getUserRecords”));
 }else{
  /* Lines of Code that gets the desired JSON via a AJAX call */
  sessionStorage.setItem(“getUserRecords”, JSON.stringify(data));
}

}

While Storing in sessionStorage we need to call the JSON.stringify function on the raw JSON object. This will convert it into string. SessionStorage stores data in the key value form where value is normally of type String.
If we do not convert it into the String, then sessionStorage stores it as [Object, Object] which is not readable.

After you have stringified the JSON and stored correctly in your sessionStorage, you may later want to convert back the value to a readable JSON format. It is when JSON.parse function is useful.

Be the first one to Comment!!!

Post a Comment