-1

I want to save an array of JSONs as a form of a cookie. For example, the array is like below.

[{"name":"Push_up", "values":{"times":35, "date":"Jan 1", "sec":3}}, 
 {"name":"Pull_up", "values":{"times":20, "date":"Mar 4", "sec":6}}]

and this is a function used for storing cookies.

function setCookie(name, value, exp=1){
    var date = new Date();
    date.setTime(date.getTime() + exp*24*60*60*1000);
    document.cookie = name + '=' + value + ';expires=' + date.toUTCString() + ';path=/';
    console.log(name + '=' + value + ';expires=' + date.toUTCString() + ';path=/');
}

I tried using Array.toString and save it as a cookie, but it isn't stringified properly so cookie is not successfully saved. How can I solve this problem?

Riddle Aaron
  • 73
  • 1
  • 2
  • 8

2 Answers2

1

To serialize JSON, you should use JSON.stringify.

But for the general case, you'd also want to escape characters with a special meaning in cookies, like =, so use escape:

document.cookie = escape(JSON.stringify(value));

But, even better - does the server really need this information, or is it only relevant to the client? If it's only relevant to the client, there's a much better solution, which is to use Local Storage, something like:

localStorage.exerciseInfo = JSON.stringify(arrOfExercises);

and retrieve it with

const arrOfExercises = JSON.parse(localStorage.exerciseInfo || '[]');

Best to use cookies only when there's information that both the client and server need to be able to read persistently, such as session or login credentials.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0
var a = [{"name":"Push_up", "values":{"times":35, "date":"Jan 1", "sec":3}}, 
 {"name":"Pull_up", "values":{"times":20, "date":"Mar 4", "sec":6}}];


JSON.stringify(a);

    "[{"name":"Push_up","values":{"times":35,"date":"Jan 1","sec":3}},
{"name":"Pull_up","values":{"times":20,"date":"Mar 4","sec":6}}]"
Sarun UK
  • 6,210
  • 7
  • 23
  • 48