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.

1
  • try like below. var tmp = {}; there is no concept of associative array in js. it is json object. Commented Jan 21, 2017 at 18:30

3 Answers 3

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))

Sign up to request clarification or add additional context in comments.

Comments

3

update your code like this

var tmp = {};

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

2 Comments

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"
please follow this link might be it will helps you stackoverflow.com/questions/11616630/…
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));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.