A
A
Alexander Pankov2015-03-11 22:22:22
JavaScript
Alexander Pankov, 2015-03-11 22:22:22

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 {

I understand that I write JSON crookedly, I need to strive like this:
{
  "christGoods": {
    "001": "4",
    "005": "9"
  }
}

I have extra {}
That's actually the question: How to organize storage in localStorage?
On click, the value itself is added (updated) to localStorage['christGood']
localStorage['christGood'] = should look like this
{
    "001": "4",
    "005": "9"
  }

And this is how the JSON.stringify function turns out for me, converting a new object (clicking on the button creates an object (an associative array) with an article number) always puts quotes in JSON format (but I don’t have to ..
I have to. Thank
christGoods: "{"007":3}{"006":1}"
you christGoods:{"007": "3","006": "1"}
in advance for your help!

Answer the question

In order to leave comments, you need to log in

5 answer(s)
D
Damir Makhmutov, 2015-03-12
@doodoo

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;
}

Use like this:
addToCart('001', 2);
getCart();
// Object {001: 2}

This is just a possible implementation example, but it works :-)

S
Sergey Sergeev, 2015-03-12
@alokazay

Json - everything must be in double quotes.

B
bromzh, 2015-03-12
@bromzh

Quotes escape

{
    "foo": "{\"inner\": [1, true, \"val\"]}",
    "bar": 2
}

S
SagePtr, 2015-03-12
@SagePtr

localStorage can only contain strings, so the object must be serialized before being placed in it. For example, the JSON.stringify function

A
Alexander Pankov, 2015-03-13
@PankovAlxndr

...//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 question

Ask a Question

731 491 924 answers to any question