2

I am trying to send json formated data over a net socket in nodejs like this:

socket.write("{\"id\":\"1\", \"type\":message, \"msg\": " + obj.msg + ", \"name\": " + obj.msg + ", \"time\": " + getDateTime() + "}", socket);

For some reason this does not work, any ideas what i am doing wrong?

Alosyius
  • 8,771
  • 26
  • 76
  • 120
  • Look into this question: http://stackoverflow.com/questions/5726729/how-to-parse-json-using-nodejs – honyovk Aug 31 '13 at 17:44

2 Answers2

1

There are few node.js modules that can help:

Simple way is to use the JSON object (ECMAScript 5) with simply converting any object to string using JSON.stringify(). Use the returned string to send over the socket.

Tal Tikotzki
  • 373
  • 3
  • 7
0
socket.write(JSON.Stringify({
   data: "stuff"
});

Then use JSON.Parse on the other side. This is how I'm doing it.

Jeff
  • 353
  • 3
  • 17
  • There is a problem with this. The tcp socket doesn't guarantee that each string you write would be separately sent. So you might receive two or more lines as part of a single message. To avoid this situation the data protocol needs to specify either the number of bytes to read or a special terminating character. – Untimely Answers Aug 23 '19 at 16:43