0

I have the following:

var cookie = $.cookie("Test_cookie");
var items = cookie ? eval("([" + cookie + "])") : [];
var jsonObj = { packageId: "11", machineId: "1", operationType: "Download" };
items.push(jsonObj);
$.cookie(cookieName, JSON.stringify(items), { expires: 1, path: '/' });

result:

[{"packageId":"11","machineId":"1","operationType":"Download"}]

which is correct.

However, when I run it the second time I want to append new object to items but json gets messed up (notice extra "["):

var jsonObj = { packageId: "11", machineId: "1", operationType: "Download" };
items.push(jsonObj);
$.cookie(cookieName, JSON.stringify(items), { expires: 1, path: '/' });

result:

[[{"packageId":"11","machineId":"1","operationType":"Download"}],{"packageId":"11","machineId":"1","operationType":"Download"}]

and it should be:

[{"packageId":"11","machineId":"1","operationType":"Download"},{"packageId":"11","machineId":"1","operationType":"Download"}]

what gives?

5
  • Some servers will alert you monthly by email - for suspicious scripts in your pages. Thanks to eval() Commented Feb 28, 2013 at 14:23
  • Try console.log(items) and paste output here. Commented Feb 28, 2013 at 14:24
  • 1
    @roXon - They should charge you monthly as well, for using eval! Commented Feb 28, 2013 at 14:24
  • @adeneo :D :D :D hahahahahah now I need another coffee ;) YMMD Commented Feb 28, 2013 at 14:27
  • I'm confused...why aren't you using JSON.parse? Commented Feb 28, 2013 at 14:28

1 Answer 1

3

Your mistake is near

var items = cookie ? eval("([" + cookie + "])") : [];

Just do

var items = cookie ? eval(cookie) : [];
Sign up to request clarification or add additional context in comments.

10 Comments

that did it!. thank you! I will accept your answer in 9 min :)
in that case the eval is quite unneeded (and dangerous tho) specially if used in combinations with cookies ;)
JSON.parse would be preferred over eval.
@JoelDuret now that you pointed it out I see I'm wrong, but in any case.... eval is not that evil if used smartly, but there's other ways to "evaluate" a string. There's always a way. using eval() is any attacker's dream and is sign of poor scripting
Joel, how would I pop from a list of json objects?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.