socket.io - is JSON a must to send an object

Problem

I have a object in the frontend and I want to broadcast it to all connected clients. Can I send it as a mere object, the way I defined it? Or do I always have to stringyfy it as JSON object before sending?

my object:

var myBox = {
         x: 400,
         y: 700,
         w: 231,
         h: 199,
         c: "red",
         ....
         }

do I need stringify?

var myBox  = JSON.stringify({

            x: 400,
            y: 700,
            ...
        });

At the moment I send it like this and the msg is a JSON:

socket.emit('message', msg);
Problem courtesy of: poppel

Solution

You can pass the object to emit without stringifying it yourself. It will be sent as plaintext, but the client callback will be passed a parsed object.

In other words, doing this is fine:

var myBox = {     
    x: 400,
    y: 700,
    w: 231,
    h: 199,
    c: "red"
}

socket.emit('message', myBox);

When listening on the client, you don't need to worry about JSON.parse:

socket.on('message', function (data) {
    alert(data.x);
});
Solution courtesy of: Asad Saeeduddin

Discussion

Yes, to send an object you will need to serialize it to a string (or ArrayBuffer, to be exact) - some sequence of bits to go over the wire (under the hood of HTTP/WS).

Yet, that serialisation does not necessarily need to be JSON.stringify, it could be anything else as well.

From what I read in their docs, Socket.io has "automatic JSON encoding/decoding" so it will do call the JSON.stringify for you, accepting plain objects as arguments to .emit as well.

Discussion courtesy of: Bergi

You can do a socket.emit with data from the object.

Like this:

socket.emit("message",{x:myBox.x,y:myBox.y, w:myBox.w, h:myBox.h, c:myBox.c});

or try:

socket.emit("message",myBox); //haven't tested it, but if it works, give plalx credit
Discussion courtesy of: Shazboticus S Shazbot

This recipe can be found in it's original form on Stack Over Flow.