You need to make sure that product
is an array and not a general object. When I do the following
var product = []; // Array
product[0] = {product_id: 1, name: "name1"};
product[1] = {product_id: 2, name: "name2"};
then JSON.stringify(product)
yields
"[{"product_id":1,"name":"name1"},{"product_id":2,"name":"name2"}]"
which is what you want to achieve.
I suspect that in your case product
is a plain object meaning that product[0]
accesses the property named 0
on the object and not the first element in an array. To illustrate this, consider the following snippet
var product = {}; // Plain JS object
product[0] = {product_id: 1, name: "name1"};
product[1] = {product_id: 2, name: "name2"};
When I run JSON.stringify(product)
in this case, it results in the output you get
"{"0":{"product_id":1,"name":"name1"},"1":{"product_id":2,"name":"name2"}}"
If you're still experiencing issues, it might be worth trying the suggestion mentioned in this question which boils down to adding
delete Array.prototype.toJSON;
at the beginning of your script.