M
M
Maxim Timofeev2017-07-25 17:21:32
JavaScript
Maxim Timofeev, 2017-07-25 17:21:32

How to debug Converting circular structure to JSON?

At some point I got an error:

error text

default_modal.js:135 Uncaught TypeError: Converting circular structure to JSON
    at JSON.stringify (<anonymous>)
    at addToCart (default_modal.js:135)
    at HTMLAnchorElement.<anonymous> (default_modal.js:75)
    at HTMLAnchorElement.dispatch (jquery.js:4737)
    at HTMLAnchorElement.elemData.handle (jquery.js:4549)
addToCart	@	default_modal.js:135
(anonymous)	@	default_modal.js:75
dispatch	@	jquery.js:4737
elemData.handle	@	jquery.js:4549


while in the line default_modal.js:135
localStorage.setItem('order_items',JSON.stringify(cart));


here is the function code:
function addToCart(data) {
        var cart = getCartObject(),
            el_name = getCartElementName(data);
        if(typeof cart[el_name] != 'undefined'){
            cart[el_name].count++;
        }else{
            cart[el_name] = data;
            cart[el_name].count = 1;
        }
        localStorage.setItem('order_items',JSON.stringify(cart));
        refreshCart();
    return true;
}

function getCartObject(){
    var cart = {};
    if (isLocalStorage()) {
        if (typeof localStorage.order_items !== 'undefined') {
            cart = JSON.parse(localStorage.order_items);
        }else{
            localStorage.order_items = JSON.stringify(cart);
        }
    }
    return cart;
}


At what everything worked, while it was localStorage.setItem, cleared it, now it should be created, it is created in the same form as it was, but it throws an error. I’ve been sitting for an hour already, I don’t understand where this creature found cyclicity.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Larisa Moroz, 2017-07-25
@webinar

Something inside the data object passed to addToCart contains a reference to the cart (or itself), forming the so-called. circular dependency, like:

var data = {
  1: "foo",
…
  d: data
}

Check what's in your cart before you doJSON.stringify(cart)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question