Ensure that the variable product
is treated as an array and not a generic object. To do this, initialize it as follows:
var product = []; // Array
product[0] = {product_id: 1, name: "name1"};
product[1] = {product_id: 2, name: "name2"};
When you use JSON.stringify(product)
, the result should be:
"[{"product_id":1,"name":"name1"},{"product_id":2,"name":"name2"}]"
This output aligns with your intended outcome.
If your situation involves product
being a simple object instead of an array, the code snippet may behave differently. For reference, take a look at the following example:
var product = {}; // Regular JS object
product[0] = {product_id: 1, name: "name1"};
product[1] = {product_id: 2, name: "name2"};
Executing JSON.stringify(product)
under these circumstances would yield the observed result:
"{"0":{"product_id":1,"name":"name1"},"1":{"product_id":2,"name":"name2"}}"
If issues persist, consider implementing a technique mentioned in this related discussion. One suggestion involves adding
delete Array.prototype.toJSON;
to the beginning of your script.