0

I have an array like this

product[0]['product_id']
product[0]['name']
....
product[1]['product_id']
product[1]['name']
...

When I use JSON.stringify(), I receive the following output

{"0":{"product_id":"1","name":"ABC"},"1":{"product_id":"1","name":"ABC"},...}

This is, however, not what I wanted to achieve because it doesn't preserver the array. Instead I want the JSON output to look like

[{"product_id":"1","name":"ABC"},{"product_id":"1","name":"ABC"},..]

How can I do that?

hennes
  • 9,147
  • 4
  • 43
  • 63
Diego
  • 81
  • 8

1 Answers1

0

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.

Community
  • 1
  • 1
hennes
  • 9,147
  • 4
  • 43
  • 63