MichaelE MichaelE - 15 days ago 7x
Javascript Question

How to handle array of objects passing to socket nodejs client

I have a nodejs/socket project which require passing of multiple arrays from the server to the client. The client uses Jquery Datatables to built tables from the arrays. If I have just one array object I can pass it ok without using stringify/parse. however, when I have multiple arrays I have a problem.

So I create an object of arrays myobjectofArrays and assign all my objectArrays to myobjectofArrays. So now they can be accessed by myobjectofArrays.objectArray1.length for example to give you the length of objectArray1. So far so good. The problem is when I try to send myobjectofArrays with:

socket.emit("arrays", {myobjectofArrays:JSON.stringify(myobjectofArrays)})

and accept it with:

var newdata=JSON.parse(data);

I get a JSON parsing error: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data.

The docs speaks to a bad JSON construct but when I do the parsing on the Server side myobjectofArrays return to an object with multiple array properties like before. and the console log of the stringified showed multiple arrays..see sample below:

console.log("myobjectofArrys json: "+myobjectofArrays);


myobjectofArrays json: {**"rpamessageArray"**:[{"messageid":0,"make":"car0","model":"Model0

Can anyone tell why am I getting this error? any help would be appreciated.


Not an expert on socket.io, but ...

Socket.emit() isn't sending JSON. Its sending an Object with one key that is a JSON string

Try to change this

socket.emit("arrays", {myobjectofArrays:JSON.stringify(myobjectofArrays)})

to this

socket.emit("arrays", JSON.stringify(myobjectofArrays))