I've been trying to work on this project to get better at coding for about half and a month now and I've come across a problem where JSON doesn't really behave the way I want it to. When I try reading a part of a JSON object, it almost always shows 'undefined' as a result.
This is the code, where I store my JSON into a cookie:
var basket = '{ "basket":['+'{ "id": 0, "data-id": 3, "amount": 1 }'+'] }';
document.cookie = 'basket='+JSON.parse(basket)+'; max-age="604800"; path=/';
I read it with:
var basket = getCookie('basket');
for(var i in basket) {
alert(basket[i]);
}
This is the last approach I've tried, this one returns the '{' (ie the first character of the JSON when I define it), meaning it behaves as if it were a string, right? In cases, where I've tried to read it with just alert(basket[0]) or alert(basket.basket[0].id) or anything (I've tried countless combinations) it almost always returns 'undefined' with the exception of only returning a part of a string.
Any ideas?
Declare basket object and while saving into cookie use JSON.stringify()
method to save it; and when you extract it from cookie use JSON.parse()
method to convert it back from string to object.
let basket = {basket:[{id: 0, dataId: 3, amount: 1 }] };
document.cookie = 'basket='+JSON.stringify(basket)+'; max-age="604800"; path=/';
function getBasketFromCookie() {
const basketValue = document.cookie
.split('; ')
.find(row => row.startsWith('basket='))
.split('=')[1];
const basketObj = JSON.parse(basketValue);
return basketObj;
}
const basketObj = getBasketFromCookie();
// print basket object
for (let key in basketObj) {
console.log(basket[key]);
}
console output:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.