Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.stringify: JSON string will be empty [duplicate]

var clients = [];

var tmp = [];

tmp["username"] = rows[0].username;
tmp["rank"] = rows[0].rank;
tmp["lastaction"] = "0";
tmp["connection"] = connection;
clients.push(tmp);

JSON.stringify(clients)

I initialized an array (clients) and pushed an associative array (tmp) to the clients array. But if I "stringify" the client, it will just return "[[]]".

What did I wrong?

Thank you in advance.

like image 326
Reese Avatar asked Feb 27 '26 22:02

Reese


1 Answers

You should turn tmp to an object literal rather than an array literal.

var clients = [];

var tmp = {};

tmp["username"] = "foo";
tmp["rank"] = 1;
tmp["lastaction"] = "0";
tmp["connection"] = "bar";
clients.push(tmp);

console.log(JSON.stringify(clients))
like image 156
Christos Avatar answered Mar 02 '26 13:03

Christos



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!