Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the reverse operation to jQuery.parseJSON();

In javaScript, using jQuery library, I need to:

  • Take an array of objects.
  • Stringify it.
  • Save it as a cookie.
  • On refresh -> Parse cookie and 'recreate' the array.

Using JSON is easy.

// Write JSON Cookie
var foo = JSON.stringify(myValue);
writeCookie(foo);

// Read [Eat?] JSON Cookie
var foo = JSON.parse(readCookie("myArray"));
if(foo.length) {
    myArray = foo;
}

(Note: writeCookie(); readCookie(); Are 2 functions I wrote based on the suggested cookie functions on quirksmode.org.)

Now, my user base involves a lot of pre-IE8 browsers. (Which won't support these methods). So I want to turn to jQuery to plug in the holes. Parsing JSON is easy:

// Read JSON Cookie with jQuery
var foo = jQuery.parseJSON(readCookie("myArray"));
if(foo.length) {
    myArray = foo;
}

My question is how do I write a JSON object to cookie using jQuery (Such that it will work for earlier versions of IE).

Thanks

Update: Still confused why jQuery would offer a parseJSON function and not a writeJSON function?

like image 424
User2 Avatar asked Oct 02 '22 01:10

User2


1 Answers

It's the native function JSON.stringify; standard jQuery does not provide a compatibility wrapper around it, but browser compatibility is not bad (will work on IE >= 8 and everything else).

like image 136
Jon Avatar answered Oct 12 '22 11:10

Jon