Mark Joseph Barnette
Mark Joseph Barnette

Reputation: 51

Can't parse JSON returned from MySQL

I have a Node.js app that is writing data to a MySQL backend. One field is an array I stringify. I can see in the workbench the data is correct when in the database. However when I retrieve it I am getting an error when I try to parse it.

"Unexpected token o in JSON at position 1"

If I log the result it shows up as [Object Object].

From what I read online this means it is already a JS object and I do not need to parse it. However I cannot find anything about how to get access to the data.

process: function (bot, msg, suffix) {

    var ftcmds = suffix.split(" ", 1);
    var ftName = ftcmds[0];
    var ftArray;
    var selectSQL = "SELECT FireTeam FROM fireteam WHERE Name = '" + ftName + "'";
    var updateSQL = "UPDATE fireteam SET FireTeam = '" + ftArray + "'WHERE Name = '" + ftName + "'";

    mysqlcon.query(selectSQL, function (err, result) {
        console.log("Result  |" + result);
        console.log("Error   |" + err);
        if (err) {
            console.log("Caught Error " + err + "  " + msg.author);
        }
        else {
            console.log("Recovered result " + result);

            ftArray = result;
            console.log("Attempting to update array");

            ftArray.push(msg.author.id);
            console.log("updated array " + ftArray);

            var jsonArray = JSON.stringify(ftArray);
            mysqlcon.query(updateSQL, function (err, result) {
                console.log("Result  |" + result);
                console.log("Error   |" + err);

                if (err.toString().indexOf(dupErr) != -1) {
                    msg.author.send("Could not find that fireteam");
                    console.log("Error: Did not locate the requested name " + msg.author)
                } else if (err) {
                    console.log("Caught Error " + err + "  " + msg.author);
                }
                else {
                    msg.author.send("You have joined Fireteam " + name + ". I will setup a group chat on " + date + " if your team fills up.");
                }
            })
        }
    });
}

Upvotes: 1

Views: 662

Answers (1)

Mark S.
Mark S.

Reputation: 4017

You should just be able to access it as an object, so if result has fields name and title you can just access them as:

var name = result.name
var title = result.title

Upvotes: 2

Related Questions