Retrieving References data from JSON-Collection of common programming errors

updates.message is a string, not a JavaScript object. You can tell by the quotes around the whole attribute. JavaScript strings don’t have a student property, so you are getting undefined. You can parse out the JSON part from the string with regular expressions and then use JSON.parse() to get the JSON object. However, the student id is also in updates.references[0].id in your example.

To get the student ID, do this:


edit: If you are really want to get the id out of the message, you need to parse it out somehow. If the message format will always be the same, you can try a regular expression or string splitting to get the part containing the id.

var id_part = json.updates.message.split(" ")[0];
//parse out just the ID number in a group
var re = /\[\[[^:]+:(\d+)\]\]/;
var matches = re.exec(id_part);
var id = matches[1];

To then get the corresponding data out of the references part, you need to loop through until you find one with the id from the message. This would work.

//Ghetto old for loop for browser compatibility
for (var i = 0; i < updates.references.length; i++) {
    if (updates.references[i].id == id) {
        //We have found the reference we want.
        //Do stuff with that reference.
        break;
    }
}

Originally posted 2013-11-09 22:46:21.