Answer the question
In order to leave comments, you need to log in
How to implement storage of JSON object inside JSON?
Hello.
Such a thing, I implement a shopping cart on the client side, use localStorage
Accordingly, I store {артикул : количествоШтук}
the whole thing in localStorage['christGoods'] = here the associative array should be ...
So that's the problem when the cart is empty (there is no christGoods key in localStorage), all oh, I start to add some product ... BUT as soon as I click on the addition of some other product (with a different article) I get an error ..
Here is a console example:
Storage {christGoods: "{"007":1}", length: 1}
Storage {christGoods: "{"007":2}", length: 1}
Storage {christGoods: "{"007":3}", length: 1}
Storage {christGoods: "{"007":3}{"006":1}", length: 1}
Uncaught SyntaxError: Unexpected token {
{
"christGoods": {
"001": "4",
"005": "9"
}
}
{
"001": "4",
"005": "9"
}
christGoods: "{"007":3}{"006":1}"
christGoods:{"007": "3","006": "1"}
Answer the question
In order to leave comments, you need to log in
You are not properly turning json into a string, or something like that.
Try this:
function addToCart(id, count) {
var cart = localStorage.getItem('christGoods');
cart = JSON.parse(cart) || {};
cart[id] = cart[id] || 0;
cart[id] += count;
localStorage.setItem('christGoods', JSON.stringify(cart));
}
function getCart() {
var cart = localStorage.getItem('christGoods');
cart = JSON.parse(cart) || {};
return cart;
}
addToCart('001', 2);
getCart();
// Object {001: 2}
localStorage can only contain strings, so the object must be serialized before being placed in it. For example, the JSON.stringify function
...//getting (calculating) article and count
new_goods[articul] = 1;
...
localStorage['christGoods'] = JSON.stringify(new_goods);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question