开发者

Retrieving References data from JSON

开发者 https://www.devze.com 2023-04-01 04:40 出处:网络
I have json data in the following format {\"updates\": {\"message\":\"[[student:123]] is present.\"}, \"references\":[{\"type\":\"student\",\"full_name\":\"XYZ\",\"id\":123}]

I have json data in the following format

{"updates":
    {"message"   :"[[student:123]] is present."},
     "references":[{"type":"student","full_name":"XYZ","id":123}]
}

How can I map the student name to the message using the id present over the message? I am relatively new to JSON parsing. I am currently using EJS template to manipulate the JSON into HTML.

In that just using

<%alert(updates.message.student)%>

returns "undefin开发者_如何学运维ed". Please help.


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:

<% alert(updates.references[0].id) %>

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;
    }
}


try

var json = {
    "updates": {
        "message": "[[student:123]] is present."
    },
    "references": [
        {
            "type": "student",
            "full_name": "XYZ",
            "id": 123
        }
    ]
};

alert(json.references[0].full_name);
0

精彩评论

暂无评论...
验证码 换一张
取 消