12

I want to persist some JSON information in browser. Depending on user interaction with the application, I want to store 5-6 different JSON object into memory. What options I have to achieve this? Please suggest any library or plugin using which I can persist information in the browser.

Thanks

SharpCoder
  • 18,279
  • 43
  • 153
  • 249

3 Answers3

14

To add to the solutions given, I'd also want to add a reference link Storing Objects in HTML5 localStorage where this question is discussed nicely.

Below is the code

var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

console.log('retrievedObject: ', JSON.parse(retrievedObject));

Courtesy: CMS

Community
  • 1
  • 1
Rupam Datta
  • 1,849
  • 1
  • 21
  • 36
  • Please note that you may loose data using this technique, this answer explains why : https://stackoverflow.com/a/122704 – Sebastien Sep 26 '22 at 08:57
6

You can use HTML5 storage which gives you both local and session storage.

Local storage persists it in a local cache and can therefore be accessed again in the future, despite the browser being closed.

Session storage will only store the information for that particular session and will be wiped once the session ends.

e.g.

//get item from storage
var foo = localStorage["bar"];

//set item in storage.
localStorage["bar"] = foo;
BenM
  • 4,218
  • 2
  • 31
  • 58
  • I would use the API instead of bracket-syntax to access single values. e.g. `if( localStorage ) { localStorage.setItem( key, value ); }` See: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage Also, be aware that there is no built-in mechanism to check the age of the entry, which maybe is important for cache invalidation. In that case one should store arrays for each value containing a timestamp. – feeela Sep 20 '13 at 09:24
  • 1
    This typically has an ~5MB limit: http://dev-test.nemikor.com/web-storage/support-test/ – icc97 Mar 10 '17 at 17:33
1

Use the HTML5 storage. This stores persistent data.

You can access it with localStorage["key"].

Shylux
  • 1,163
  • 2
  • 16
  • 31