javascript 将压缩的 json 数据存储在本地存储中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20773945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Storing compressed json data in local storage
提问by Rajeev
I want to store JSON data in local storage. Sometimes data stored could be more than 5MB(max threshold allowed by browsers for each domain). Is there anyway i can compress or zip the data and store it in local storage ? How much latency it will add if compression and decompression for every JS function on large data ?
我想将 JSON 数据存储在本地存储中。有时存储的数据可能超过 5MB(每个域的浏览器允许的最大阈值)。无论如何我可以压缩或压缩数据并将其存储在本地存储中吗?如果对大数据的每个 JS 函数进行压缩和解压缩,它会增加多少延迟?
I am using this json data to display on webpage..... It is like a static data which is mostly same for entire session. we provide actions like search, filter etc on this json data...Whenever user enters a keyword, i search in this json data which is stored in local storage instead of making call to server
我正在使用此 json 数据在网页上显示..... 它就像一个静态数据,对于整个会话几乎相同。我们在此 json 数据上提供搜索、过滤等操作...每当用户输入关键字时,我都会在此 json 数据中搜索存储在本地存储中的数据,而不是调用服务器
采纳答案by Raunak Kathuria
As localStorage functionality seems to be limited to handle only string key/value pairs what you can do is to use lz-string libraryto stringify the json object and compress it before storing it in localStorage
由于 localStorage 功能似乎仅限于处理字符串键/值对,您可以做的是使用lz-string 库对 json 对象进行字符串化并在将其存储在 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
检查 jsfiddle http://jsfiddle.net/raunakkathuria/7PQtC/1/因为我已经复制了完整的脚本,所以在小提琴的末尾寻找正在运行的代码
Use compressToUTF16
and decompressFromUTF16
if you are dealing with UTF characters but please note that the strings produced are therefore 6.66% bigger than those produced by compress
. So use utf
ones only when required.
如果您正在处理 UTF 字符,请使用compressToUTF16
anddecompressFromUTF16
但请注意,生成的字符串因此比compress
. 因此utf
,仅在需要时才使用它们。