Ali
Ali

Reputation: 103

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

Upvotes: 3

Views: 12800

Answers (2)

fflorent
fflorent

Reputation: 1646

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).

Upvotes: 12

Bartek
Bartek

Reputation: 15599

What browser? What environment? Just plugged your data into Chrome Inspector, works fine..

debug

Upvotes: -1

Related Questions