Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing compressed json data in local storage

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 ?

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

like image 884
Rajeev Avatar asked Dec 25 '13 14:12

Rajeev


People also ask

Can you save JSON in local storage?

Storing JSON, Functions And Arrays in localStorage Luckily, we can store complex data in localStorage by leveraging the JSON object's stringify() and parse() functions. JSON support is quite good on mobile but if you need to add support use json2.

Is JSON a good way to store data?

JSON is perfect for storing temporary data. For example, temporary data can be user-generated data, such as a submitted form on a website. JSON can also be used as a data format for any programming language to provide a high level of interoperability.

Are JSON files compressed?

As text data, JSON data compresses nicely. That's why gzip is our first option to reduce the JSON data size. Moreover, it can be automatically applied in HTTP, the common protocol for sending and receiving JSON.

Can you store JSON?

You can store JSON documents in SQL Server or SQL Database and query JSON data as in a NoSQL database.


1 Answers

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

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.

like image 51
Raunak Kathuria Avatar answered Sep 17 '22 04:09

Raunak Kathuria