Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Dangerous stuff!
- // Turn object in JSON form into a string for storage
- JSON.serialize = function (jsonObject) {
- var property = null,
- current = null,
- jsonAsArray = [],
- propertyType = '';
- for (property in jsonObject) {
- current = jsonObject[property];
- propertyType = typeof(current);
- // If the property is just a string, we simply toss quotes around it.
- if (propertyType == 'string') {
- current = '"' + current + '"';
- }
- // If the property is an object and isn't null we recurse
- else if (propertyType == 'object' && current !== null) {
- current = JSON.serialize(current);
- }
- // Add whatever's left to the array object as a key value pair.
- jsonAsArray.push(('"' + property + '":') + current);
- }
- // Wrap the contents in the proverbial braces so we have an object
- // representation.
- return('{' + jsonAsArray.toString() + '}');
- };
- // Turn a JSON string into a JSON Object.
- JSON.deserialize = function (jsonString) {
- if (jsonString === '') {
- jsonString = '""';
- }
- // I don't know how to avoid this, but we should.
- eval('var evil=' + jsonString + ';');
- // Bwah ha ha.
- return evil;
- };
- window.addEventListener('load', function() {
- // Enable on first load, disable after to test properly.
- //var testJSON = {
- // testString: 'stringTest',
- // funTest: function() {
- // alert('hi');
- // },
- // alertAgain: function() {
- // alert('again!');
- // }
- //};
- //var jsonString = JSON.serialize(testJSON);
- //localStorage.setItem('funTest', jsonString);
- var jsonObj = JSON.deserialize(localStorage.getItem('funTest'));
- jsonObj.funTest();
- jsonObj.alertAgain();
- console.log(jsonObj.testString);
- // Enable to clear the storage
- //localStorage.clear();
- }, false);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement