如何在javascript中从cookie中检索Json数据?

如何在javascript中从cookie中检索Json数据?,javascript,json,cookies,Javascript,Json,Cookies,这是一个添加到cookie的购物车,但我不清楚这个,而且当我单击refresh和addtocart onclick函数时,所有cookie值都将被覆盖 我的目标是, cookievalue=[{id:1,价格:33,数量:1},{id:1,价格:33,数量:1},{id:1,价格:33,数量:1}] var cartstring={}; var jsonstring=[] var addtocart = (function(id,price,qty) { cartstring.i

这是一个添加到cookie的购物车,但我不清楚这个,而且当我单击refresh和addtocart onclick函数时,所有cookie值都将被覆盖

我的目标是, cookievalue=[{id:1,价格:33,数量:1},{id:1,价格:33,数量:1},{id:1,价格:33,数量:1}]

var cartstring={}; var jsonstring=[]

var addtocart = (function(id,price,qty)
{
        cartstring.id = id;
        cartstring.price = price;
        cartstring.qty = qty;
        /* Also check here whether the cookie having data then the new value will be pushed and then inserted to cookie */
        jsonstring = JSON.stringify(cartstring); 

        var d = new Date();
        d.setTime(d.getTime() + (3600 * 24 * 60 * 60 * 1000));
        var expires = "expires="+d.toUTCString();
        document.cookie = "cartObj=" + jsonstring + ";" + expires + ";path=/";
});

非常感谢您的关注,先生/女士

如何写入和读取json数据的快速示例

const data = {
    int: 22,
    obj: { name: 'bar' },
    arr: [0,1,2,3,4,5]
}


//  write cookie
document.cookie = `json=${JSON.stringify(data)}`; 

//  read all cookie values
console.log(document.cookie)

//  read json string value from cookie
console.log(document.cookie.split('json=')[1].split(';')[0]); 

//  parse json string value to object
console.log(JSON.parse(document.cookie.split('json=')[1].split(';')[0])); 

分享一些您尝试过的代码,或者准备好下载。另外:欢迎使用Stackoverflow。