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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.