Advertisement
javecantrell

JavaScript Web Storage

Sep 15th, 2014
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Dangerous stuff!
  2.  
  3. // Turn object in JSON form into a string for storage
  4. JSON.serialize = function (jsonObject) {
  5.         var property = null,
  6.             current = null,
  7.             jsonAsArray = [],
  8.             propertyType = '';
  9.  
  10.         for (property in jsonObject) {
  11.             current = jsonObject[property];
  12.             propertyType = typeof(current);
  13.  
  14.             // If the property is just a string, we simply toss quotes around it.
  15.             if (propertyType == 'string') {
  16.                 current = '"' + current + '"';
  17.             }
  18.             // If the property is an object and isn't null we recurse
  19.             else if (propertyType == 'object' && current !== null) {
  20.                 current = JSON.serialize(current);
  21.             }
  22.             // Add whatever's left to the array object as a key value pair.
  23.             jsonAsArray.push(('"' + property + '":') + current);
  24.         }
  25.         // Wrap the contents in the proverbial braces so we have an object
  26.         // representation.
  27.         return('{' + jsonAsArray.toString() + '}');
  28. };
  29.  
  30. // Turn a JSON string into a JSON Object.
  31. JSON.deserialize = function (jsonString) {
  32.     if (jsonString === '') {
  33.         jsonString = '""';
  34.     }
  35.     // I don't know how to avoid this, but we should.
  36.     eval('var evil=' + jsonString + ';');
  37.  
  38.     // Bwah ha ha.
  39.     return evil;
  40. };
  41.  
  42.  
  43. window.addEventListener('load', function() {
  44.     // Enable on first load, disable after to test properly.
  45.     //var testJSON = {
  46.     //    testString: 'stringTest',
  47.     //    funTest: function() {
  48.     //        alert('hi');
  49.     //    },
  50.     //    alertAgain: function() {
  51.     //        alert('again!');
  52.     //    }
  53.     //};
  54.     //var jsonString = JSON.serialize(testJSON);
  55.     //localStorage.setItem('funTest', jsonString);
  56.  
  57.     var jsonObj = JSON.deserialize(localStorage.getItem('funTest'));
  58.     jsonObj.funTest();
  59.     jsonObj.alertAgain();
  60.     console.log(jsonObj.testString);
  61.  
  62.     // Enable to clear the storage
  63.     //localStorage.clear();
  64.  
  65. }, false);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement