Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.stringify throws error

var Products = [
    { id: 0, product: 'Sour Apple', price: 10, count: 1, product_thumb: 'resources/css/apple.png' },
    { id: 1, product: '30 dsfdf', price: 20, count: 1, product_thumb: 'resources/css/croissant.png' },
    { id: 2, product: 'Discount Coffee', price: 30, count: 1, product_thumb: 'resources/css/coffecup.png' },
    { id: 3, product: '30 Donut Combo', price: 40, count: 1, product_thumb: 'resources/css/donut.png' },
    { id: 4, product: 'Invisishield', price: 50, count: 1, product_thumb: 'resources/css/apple.png' },
    { id: 5, product: 'Pink Cupcake', price: 60, count: 1, product_thumb: 'resources/css/icecream.png' },
    { id: 6, product: 'Strawberry Cone', price: 70, count: 1, product_thumb: 'resources/css/softy.png' }
]

I am trying to encode the product array (above) to JSON string and I am getting the following error: TypeError: Converting circular structure to JSON

UPDATE (from comment):

What i am trying to do is, i declare a var product = []; and then as and when user add's product to cart i do: var productObject = { id: id, product: name, price: price, count: 1, product_thumb: img }; Once the user says done, i take the array and want to convert it to json and send it to my web service. The problem is when i do JSON.stringify it gives that error. product.push(productObject);

like image 996
Ali Avatar asked Jun 25 '26 05:06

Ali


1 Answers

TypeError: Converting circular structure to JSON

This error occurs when you have a cycle in your object. For example :

var obj = {};
obj.a = {b:obj};

If you browse obj, you have that cycle : obj->a->b->obj->...

So, JSON.stringify(obj) raises an error.

That kind of error can also occur when you include a DOM Object (window, document...), since they or their children reference them(self).

like image 65
fflorent Avatar answered Jun 26 '26 18:06

fflorent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!