When I send a JSON string via websocket (Socket.io) from a Node.js server to a client's browser, I find that I have to execute the JSON.parse function twice in order to extract an object from the received JSON string. This behavior is confusing to me.
The server is responsible for sending a JSON string to the client:
dataString = '{"test": [ {"M": "A", "R": "e", "B": "e", "C": "e", "K": "e", "BD": "e", "CYC": "e"},{"M": "B", "R": "e", "B": "e", "C": "e", "K": "e", "BD": "e", "CYC": "e"}, {"M": "C", "R": "e", "B": "e", "C": "e", "K": "e", "BD": "e", "CYC": "e"},{"M": "D", "R": "e", "B": "e", "C": "e", "K": "e", "BD": "e", "CYC": "e"}]}'
let data = JSON.stringify(dataString);
socket.emit('test', data );
Upon receiving the string on the client side, it appears as follows:
"{\"test\": [ {\"M\": \"A\", \"R\": \"e\", \"B\": \"e\", \"C\": \"e\", \"K\": \"e\", \"BD\": \"e\", \"CYC\": \"e\"},{\"M\": \"B\", \"R\": \"e\", \"B\": \"e\", \"C\": \"e\", \"K\": \"e\", \"BD\": \"e\", \"CYC\": \"e\"}, {\"M\": \"C\", \"R\": \"e\", \"B\": \"e\", \"C\": \"e\", \"K\": \"e\", \"BD\": \"e\", \"CYC\": \"e\"},{\"M\": \"D\", \"R\": \"e\", \"B\": \"e\", \"C\": \"e\", \"K\": \"e\", \"BD\": \"e\", \"CYC\": \"e\"}]}\n"
To extract an object, I find that I need to execute the json.parse function twice. The first time, I receive a string:
{"test": [ {"M": "A", "R": "e", "B": "e", "C": "e", "K": "e", "BD": "e", "CYC": "e"},{"M": "B", "R": "e", "B": "e", "C": "e", "K": "e", "BD": "e", "CYC": "e"}, {"M": "C", "R": "e", "B": "e", "C": "e", "K": "e", "BD": "e", "CYC": "e"},{"M": "D", "R": "e", "B": "e", "C": "e", "K": "e", "BD": "e", "CYC": "e"}]}
Here is the code on the client side:
socket.on('test', function (message) {
var rec = message;
var transfer = JSON.parse(rec);
alert(transfer);
var transfer = JSON.parse(transfer);
alert(transfer);
})