Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bug when sending array in node.js and socket.io

I use socket.io version 0.8.4

I have boiled down my problem to the following. I have data looking like this:

data.prop1 = [];
data.prop1.push("man");
data.prop2 = [];
data.prop2["hey"] = "man";

I send the data from the server to the client this way:

socket.emit("data", data);

On the client side I receive the data this way:

socket.on("data", function(data){ console.log(data); });

The weird thing is:

data.prop1 = [];
data.prop1.push("man"); // This data exists in the client side data object
data.prop2 = [];
data.prop2["hey"] = "man"; // This data does not exist.

data.prop2 is just an empty array on the client side.

Is there a known bug in json serializing arrays on the form in prop2?

Thankyou in advance

EDIT:

Problem solved using this workaround:

data.prop1 = [];
data.prop1.push("man");
data.prop2 = {}; // <= Object instead of array
data.prop2["hey"] = "man";
like image 600
Stephan Møller Avatar asked Jan 14 '12 20:01

Stephan Møller


2 Answers

ECMA-262 about JSON.stringify:

The representation of arrays includes only the elements between zero and array.length – 1 inclusive. Named properties are excluded from the stringification.

Arrays are supposed to have numerical property names. So when the data.prop2 is transformed to JSON (which socket.io sends the data in, I imagine), it doesn't get the 'hey' property. If you want to use non-numerical property names, you should use objects instead of arrays:

data.prop1 = [];
data.prop1.push("man");
data.prop2 = {}; // Notice we're creating an object, not an array.
data.prop2["hey"] = "man"; // Alternatively: data.prop2.hey = "man"
like image 86
Felix Loether Avatar answered Oct 22 '22 07:10

Felix Loether


Unfortunately, Javascript doesn't really work like that.

Check out this article, about half way down. It explains the problem where you try to set data.prop2["hey"] = "man";

like image 41
Dustin Graham Avatar answered Oct 22 '22 06:10

Dustin Graham