Storing compressed json data in local storage

隐身守侯 提交于 2019-12-02 20:38:32

As localStorage functionality seems to be limited to handle only string key/value pairs what you can do is to use lz-string library to stringify the json object and compress it before storing it in localStorage

Usage

// sample json object
var jsonobj = {'sample': 'This is supposed to be ling string', 'score': 'another long string which is going to be compressed'}

// compress string before storing in localStorage    
localStorage.setItem('mystring', LZString.compress(JSON.stringify(jsonobj)));

// decompress localStorage item stored
var string = LZString.decompress(localStorage.getItem('mystring'))

// parse it to JSON object
JSON.parse(string);

Check jsfiddle http://jsfiddle.net/raunakkathuria/7PQtC/1/ as i have copied the complete script so look for running code at end of fiddle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!