简体   繁体   English

javascript将json对象推送到数组

[英]javascript push json object to array

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 "["): 但是,当我第二次运行它时,我想将新对象添加到项目中,但是json混乱了(注意额外的“ [”):

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? 是什么赋予了?

Your mistake is near 你的错误就近了

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

Just do 做就是了

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM