Categories
JavaScript Answers

How to store compressed JSON data in local storage with JavaScript?

Spread the love

Sometimes, we want to store compressed JSON data in local storage with JavaScript.

In this article, we’ll look at how to store compressed JSON data in local storage with JavaScript.

How to store compressed JSON data in local storage with JavaScript?

To store compressed JSON data in local storage with JavaScript, we can use the lz-string library.

For instance, we write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lz-string/1.4.4/lz-string.min.js"></script>

to add the library script.

Then we write:

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

localStorage.setItem('mystring', LZString.compress(JSON.stringify(jsonobj)));

const string = LZString.decompress(localStorage.getItem('mystring'))
console.log(JSON.parse(string));

to call LZString.compress to compress the stringified version of jsonobj.

Then we decompress the string with LZString.decompress.

And then we call JSON.parse to parse the decompressed string.

Conclusion

To store compressed JSON data in local storage with JavaScript, we can use the lz-string library.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *