使用javascript解析JSON并获取数组中的特定值

时间:2016-06-06 08:13:20

标签: javascript php arrays json parsing

在我的控制台日志中,数组如下所示:

{"userid":"5502","fullname":"My fullname","email":"sample@yahoo.com","user_access":"real"}

现在在我的ajax上,我有一个服务器发送给应用程序的数据数组的句柄代码:

function handleData(responseData) {
    var access = responseData;

    console.log(access);
    if (access == '"real"') {
        alert("Welcome");
        location.href = "home.html";
    } else {
        alert("Your username and password didn\'t match.");
    }
}

如何在数组中获取此"user_access":"real"的具体值并在条件中使用它。

像这样:

if (access == '"real"') { // What should be the format of access variable?
    alert("Welcome");
    location.href = "home.html";
}

2 个答案:

答案 0 :(得分:4)

function handleData(responseData) {
                var response = JSON.parse(responseData);//assuming you are getting the response as a string

                var access = response.user_access;    
                console.log(access);

                if (access == "real") {
                    alert("Welcome");
                    location.href = "home.html";    
                } else {
                    alert("Your username and password didn\'t match.");
                }    
            }//handleData()

通常,我们希望我们的响应是在json(或者我们可以说是' object')形式,以便我们可以轻松访问其内部属性。因此,如果它已经是对象,则不需要使用JSON.parse。您可以直接访问此类任何属性 - responseData.user_access。但如果它是字符串形式,则必须先使用JSON.parse()将字符串解析为JSON(或对象)格式。

答案 1 :(得分:1)

如果没有""围绕{}括号然后只做

function handleData(responseData) {
    var access = responseData.access;
    if (access === 'real') {
        alert("Welcome");
        location.href = "home.html";
    } else {
        alert("Your username and password didn\'t match.");
    }
}