Oliver Dixon
Oliver Dixon

Reputation: 7424

SocketIO cannot access JSON properties from ON

I don't know if I'm going crazy here but I'm doing something very basic that would usually be trivial, but I've been stuck on it for awhile now.

I'm receiving a message from a client like so:

            socket.on('request_username', function(messageFromClient) {

            if(messageFromClient == undefined) {
                Logger.logError("messageFromClient was undefined in socket_api.js");
                return;
            }

            // Parse the message into Json, might not be needed.
            // Logs: "{\"username\":\"test\"}"
            console.log(messageFromClient);

            try {
                messageFromClient = JSON.parse(messageFromClient);
                //Logs: {"username":"test"}
                console.log(messageFromClient);
            } catch(err) {
                console.log("Error parsing json from request_username. Mesage is %s", err);
                return;
            }

        // All undefined.
        console.log(messageFromClient['"username"']);
        console.log(messageFromClient["username"]);
        console.log(messageFromClient['username']);

            // msg == undefined incase the parse failed.
            if(messageFromClient == undefined || messageFromClient.username == undefined) {
                Logger.logError("messageFromClient.username was undefined in socket_api.js");
                return;
            }

            var usernameRequested = messageFromClient.username;

Now I'm getting this in the logs

"{\"username\":\"test\"}"
{"username":"test"}
Log Error: messageFromClient.username was undefined in socket_api.js

I've no idea what I'm doing wrong..

Upvotes: 0

Views: 987

Answers (1)

jfriend00
jfriend00

Reputation: 707856

With socket.io, it automatically serializes Javascript data to/from JSON. You do not have to do that and if you attempt to, you can mess things up.

In socket.io, you can send like this:

var data = {username: "test"};
socket.emit('request_username', data);

Then, on the receiving side, you would have:

socket.on('request_username', function(data) {
    console.log(data.username);   // will show "test"
});

The serializing to/from JSON is done automatically by the socket.io library (one of its many useful features).


To debug your particular situation further, we will need to know exactly what the very first console.log(messageFromClient) shows right when the message first arrives before you've done anything to it?

You show a bunch of log info, but it's not entirely clear which debug line corresponds with which line of code. If that very first console.log shows:

"{\"username\":\"test\"}"

then your message is apparently still JSON which is probably because it was doubly JSON encoded which is an error on the sending side. This should be fixed on the sending side rather than trying to double parse it.


Also, when discussing this problem please be aware that JSON is a string format. A Javascript object is something you can directly access properties on in Javascript code. It appears you are sometimes calling them both JSON which is confusing for all. You convert a Javascript object to JSON with var jsonStr = JSON.stringify(obj) and you convert JSON to a Javascript object with var obj = JSON.parse(someJSON).

var obj = {username: test};           // Javascript object
var jsonStr = JSON.stringify(obj);    // produces a JSON string
var obj2 = JSON.parse(jsonStr);       // parses JSON string back to a Javascript object

Upvotes: 1

Related Questions