Jump to content

Help with json data


shortysbest

Recommended Posts

I am using nodejs and websockets, and I am new to this and I am trying to make some tests with it, what I need help with is handling json data (I'm also quite new to json data as well) So what I'm doing is sending json data to my node.js websocket server, the problem I'm having is getting the information out. I log the variable it receives in the console and it shows:

 

{ type: 'utf8',
  utf8Data: '{"data":{"msg":"hey","userID":881}}' }

 

So I need to somehow get the msg data "hey" and the userID data "881" but it doesn't seem to be working, I have however been able to do this on the reverse side, on the client end of the javascript handling.

 

Here's the code I'm trying to make work:

( I have commented through it to show my problem and intentions.

 

connection.on('message', function(message) {

console.log(message); // <--- This returns: { type: 'utf8', utf8Data: '{"data":{"msg":"hey","userID":881}}' }

//The message variable in the function above is the json, I then are trying to pass the data to a new json object to return to users

var obj = { 
		text: message.data.msg,  //This should be: "hey"  instead i get an error sent to my console: text: message.data.msg, TypeError: Cannot read property 'msg' of undefined
		id: message.data.userID //This should be "881" 
	  };

// broadcast message to all connected clients
var json = JSON.stringify({ type:'message', data: obj });
for (var i=0; i < clients.length; i++)
{
	clients[i].sendUTF(json);
}

 

 

Thanks.

Link to comment
https://forums.phpfreaks.com/topic/253471-help-with-json-data/
Share on other sites

Upon trying more things, I have noticed this:

 

When I have the console with this:

console.log(message);

it returns:

{ type: 'utf8', utf8Data: '{"data":{"msg":"hey","userID":881}}' }

 

When I have the console with this:

console.log(message.utf8Data);

it returns:

{"data":{"msg":"hey","userID":881}}

 

Then I have the console with this:

console.log(message.utf8Data.data);

it returns "undefined";

 

the same when I add "msg" to the end of the console.log

Link to comment
https://forums.phpfreaks.com/topic/253471-help-with-json-data/#findComment-1299303
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.