0

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:

socket.on('arrays',function(data)
       {
        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);

result:

myobjectofArrays json: {**"rpamessageArray"**:[{"messageid":0,"make":"car0","model":"Model0
","part":"Part0","price":"9999.99","instock":false},{"messageid":1,"make":"car1"
,"model":"Model1","part":"Part1","price":"9999.99","instock":false},{"messageid"
:2,"make":"car2","model":"Model2","part":"Part2","price":"9999.99","instock":fal
se},},{"messageid":3,".........,"price":"9999.99","instock":false}],"}],"**ordersArray**":[{"messageid":0,"ordernumber"
:0,"customer":"name0","contact":"555-1230","make":"car0","model":"Model0","part"
:"Part0","price":"9999.99","shipping":"Pickup","payment":"cc-mobile","confirm":t
rue},{"messageid":1,"ordernumber":1,"customer":"name1","contact":"555-1234","mak
e":"car1","model":"Model1","part":"Part1","price":"9999.99","shipping":"Pickup",
"payment":"cc-mobile","confirm":true},{".........]

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

1
  • don't aspect your json didn't mutate in transit. console.log the data before parse client side and see what it looks like. Commented Oct 9, 2016 at 20:37

1 Answer 1

3

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.