Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
 
Some servers will alert you monthly by email - for suspicious scripts in your pages. Thanks to eval() –  Roko C. Buljan Feb 28 '13 at 14:23
 
Try console.log(items) and paste output here. –  ATOzTOA Feb 28 '13 at 14:24
1  
@roXon - They should charge you monthly as well, for using eval! –  adeneo Feb 28 '13 at 14:24
 
@adeneo :D :D :D hahahahahah now I need another coffee ;) YMMD –  Roko C. Buljan Feb 28 '13 at 14:27
 
I'm confused...why aren't you using JSON.parse? –  Ian Feb 28 '13 at 14:28
add comment

1 Answer

up vote 2 down vote accepted

Your mistake is near

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

Just do

var items = cookie ? eval(cookie) : [];
share|improve this answer
 
that did it!. thank you! I will accept your answer in 9 min :) –  Shane Km Feb 28 '13 at 14:24
2  
in that case the eval is quite unneeded (and dangerous tho) specially if used in combinations with cookies ;) –  Roko C. Buljan Feb 28 '13 at 14:25
 
Are you sur roXon? "cookie" just contain STRING... –  JoDev Feb 28 '13 at 14:26
1  
JSON.parse would be preferred over eval. –  David Hedlund Feb 28 '13 at 14:29
 
@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 –  Roko C. Buljan Feb 28 '13 at 14:29
show 6 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.