Storing JSON data in session storage

Storage data:

sessionStorage.setItem("loginInfo",JSON.stringify(bdata));

Get data

var loginObj=JSON.parse(sessionStorage.getItem('loginInfo'));

In web development, session storage is often used to store data, so it is not difficult to store a single string data variable

var str = 'This is a string';
sessionStorage.setItem('param',str);

Get sessionstorage

var item = sessionStorage.getItem('param');
console.log(item);

However, sessionstorage can only store string type data, and can’t directly store array types and JSON objects. If there is a need, what should I do?It’s very simple.

First, the JSON object is passed through JSON.stringify () method is converted to a string and stored in sessionstorage

var obj = {
  "name": "Tom",
  "age": 12,
  "gender": "man"
};
sessionStorage.setItem('jsonParams',JSON.stringify(obj));

And then through JSON.parse () method to convert the string to JSON format

var data = JSON.parse(sessionStorage.getItem('jsonParams'));
console.log(data);

Read More: