Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save json to chrome storage / local storage

I want to save json to chrome or local storage. I also need to be able too add items without losing the others.

like image 550
Theo Sandell Avatar asked Jan 22 '16 16:01

Theo Sandell


People also ask

Can you save JSON in local storage?

In summary, we can store JavaScript objects in localStorage by first converting them to strings with the JSON. stringify method, then back to objects with the JSON. parse method.

Does Chrome support local storage?

Google Chrome/ChromiumChrome treats cookies and local storage as the same thing, so these steps work for both. Click on the menu button in the top-right corner of your Chrome window. Select “Settings” from that menu. Click “Cookies and site permissions”.

How do I add local storage to Chrome?

Just go to the developer tools by pressing F12 , then go to the Application tab. In the Storage section expand Local Storage. After that, you'll see all your browser's local storage there.


2 Answers

Updated

var local = (function(){

    var setData = function(key,obj){
        var values = JSON.stringify(obj);
        localStorage.setItem(key,values);
    }

    var getData = function(key){
        if(localStorage.getItem(key) != null){
        return JSON.parse(localStorage.getItem(key));
        }else{
            return false;
        }
    }

    var updateDate = function(key,newData){
        if(localStorage.getItem(key) != null){
            var oldData = JSON.parse(localStorage.getItem(key));
            for(keyObj in newData){
                oldData[keyObj] = newData[keyObj];
            }
            var values = JSON.stringify(oldData);
            localStorage.setItem(key,values);
        }else{
            return false;
        }
    }

    return {set:setData,get:getData,update:updateDate}
})();

how do you use?

When you want to set a value:

var a = {'test':123};
local.set('valueA',a);

When you want to get the value:

var a = local.get('valueA')

When you want to update a value or insert a new one

var b = {'test':333,'test2':555};
local.set('valueA',b);
like image 154
Luan Soares Avatar answered Oct 03 '22 05:10

Luan Soares


try this code:

// Object to store
var person = {
  'name': 'Dan',
  'age': 20,
  id: 7644
};

var value = JSON.stringify(person);
var key = person.id;

// Set person object into storage
localStorage.setItem(key, value);

// Get person object from storage
var personFromStorage = localStorage.getItem(key);

personFromStorage = JSON.parse(personFromStorage);

alert(personFromStorage.name);
like image 32
ofir fridman Avatar answered Oct 03 '22 06:10

ofir fridman