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

Reese
  • 253
  • 5
  • 15
  • try like below. var tmp = {}; there is no concept of associative array in js. it is json object. – rajesh Jan 21 '17 at 18:30

3 Answers3

5

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))
Christos
  • 53,228
  • 8
  • 76
  • 108
3

update your code like this

var tmp = {};

Asssociative array has not support directly in javascript you can make as object

Man Programmer
  • 5,300
  • 2
  • 21
  • 21
  • Thank you, but this throws an error when sending it to the node.js client: connection.sendUTF(JSON.stringify({response: "loginsucceed", onlinelist: JSON.stringify(clients)})); "TypeError: Converting circular structure to JSON" – Reese Jan 21 '17 at 18:35
  • 1
    please follow this link might be it will helps you http://stackoverflow.com/questions/11616630/json-stringify-avoid-typeerror-converting-circular-structure-to-json – Man Programmer Jan 21 '17 at 18:38
1

You need to initialize tmp as an object:

var clients = [];

var tmp = {};

tmp["username"] = 'username';
tmp["rank"] = 1
tmp["lastaction"] = 2
tmp["connection"] = 3
clients.push(tmp);

console.log(JSON.stringify(clients));
Max Sindwani
  • 1,267
  • 7
  • 15