Reputation: 1391
I keep getting undefined when I attempt to output the objects value via chrome console. Code:
ws.on('message', function(message) {
var JSONobj = {"cmd":"updatesb","name":"TestName"};
console.log('JSON Name Value: %s', message.name); //<--does not work
console.log('JSON Name Value: %s', JSONobj.name); //<----WORKS!!!!
});
The message argument in ws.on passes {"cmd":"updatesb","name":"TestName"} via websocket communication. The first console output is undefined. The second output is TestName. Why is message.name undefined when it should have a value of TestName and how do I get the value from message.name?
Upvotes: 1
Views: 2178
Reputation: 35135
Try:
message.name = 'xxx';
console.log('JSON Name Value: %s', message.name);
to see if the message.name
succeeds. As others pointed out, message
is most likely not what you think.
Try also console.log(message);
and examine the output.
Also, it may be that the on
handler receives more then just the message so the handler should in fact look like function(something_else, message)
, but it is hard to know without knowing what ws is.
Upvotes: 0
Reputation: 888185
It sounds like your message
parameter is a string, not an object.
You can parse that string as JSON by calling JSON.parse()
.
Upvotes: 5