I want to save json to chrome or local storage. I also need to be able too add items without losing the others.
Asked
Active
Viewed 8,619 times
6
-
possible duplicate of this: http://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage – metame Jan 22 '16 at 16:17
-
Basically you can only store key/value strings in HTML5 localstorage – metame Jan 22 '16 at 16:17
-
https://developer.chrome.com/extensions/storage – Daniel Herr Jan 22 '16 at 17:12
3 Answers
8
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);

Luan Soares
- 310
- 2
- 6
2
// 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);

ofir fridman
- 2,691
- 2
- 17
- 27
0
What you want to do is simple with localDataStorage, where you can transparently set/get any of the following "types": Array, Boolean, Date, Float, Integer, Null, Object or String.
[DISCLAIMER] I am the author of the utility [/DISCLAIMER]
Examples:
localDataStorage.set( 'key1', 'Belgian' );
localDataStorage.set( 'key2', 1200.0047 );
localDataStorage.set( 'key3', true );
localDataStorage.set( 'key4', { 'RSK' : [1,'3',5,'7',9] } );
localDataStorage.set( 'key5', null );
localDataStorage.get( 'key1' ); --> 'Belgian'
localDataStorage.get( 'key2' ); --> 1200.0047
localDataStorage.get( 'key3' ); --> true
localDataStorage.get( 'key4' ); --> Object {RSK: Array(5)}
localDataStorage.get( 'key5' ); --> null
All of the conversion work is done in the background for you: all you have to do is set & get. Type conversion is performed on-the-fly.

Mac
- 1,432
- 21
- 27