Javascript Can we set javascript objects in cookies?

I am trying to put a single javascript object in Cookies, but somehow it is converted as a String object. Is there a way to set objects in JavaScript cookies?

+2
source share
4 answers

You can convert the object to JSON before saving to cookies and convert from JSON to Object after receiving cookies.

+4
source

You can use JSON.stringify()to turn an object into a JSON string and save it. Then, after reading them, translate the string into an object usingJSON.parse()

LocalStorage cookie . , cookie - 4 , LocalStorage - 5-10 .

+5

this function converts an object into a string, using it to strengthen the object and then add it to the cookie.

function JSONToString(Obj){

var outStr ='';
for (var prop in Obj) {
    outStr = '{';
    if (Obj.hasOwnProperty(prop)) {
        if(typeof Obj[prop] == 'object'){
            outStr += JSONToString(Obj[prop]);
        } else {
            outStr += prop + ':' + Obj[prop].toString();
        }
    }  
    outStr += '}';
}
return outStr;
}
+1
source

Use JSON - Designation of a JavaScript object. Here is a good tutorial on using JSON .

Long things are short: this is the standard for converting any object to a specially formatted text string and vice versa. That way you would save the JSON string in a cookie.

0
source

Source: https://habr.com/ru/post/1793162/


All Articles