【问题标题】:Parse JSON using javascript and get specific value in array使用 javascript 解析 JSON 并获取数组中的特定值
【发布时间】:2016-10-05 18:30:14
【问题描述】:

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

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

【问题讨论】:

  • if (access.access == "real") ....
  • responseData.access === 'real'
  • 那不是数组而是对象..使用Property accessors访问object的属性
  • 您的问题(示例对象)不准确。您已经询问了如何检查 access 属性,而实际上您需要 user_access 属性。
  • @evolution,是的,我错误地输入了我在代码中使用的真实对象。还是谢谢。

标签: javascript php arrays json parsing


【解决方案1】:
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(或对象)格式。

【讨论】:

  • console.log(access);它是未定义的。
  • 你能粘贴这两行的输出吗:console.log(responseData); console.log( typeof responseData );
  • console.log( responseData ) ; --> {"user_id":"5502","user_fullname":"我的全名","user_email":"sample@yahoo.com","user_access":"real"} console.log( typeof responseData ); --> 字符串
  • 好的,所以它没有access 属性,而是user_access。我已经相应地更新了我的答案。请再试一次。
  • 嗨@Mike,抱歉刚刚回去工作。它现在正在工作,谢谢你帮助我。我的错误我在我的例子中写了错误的对象。应该是 user_access 而不是 access。
【解决方案2】:

如果它没有被 {} 括号周围的“”包围,那么就这样做

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.");
    }
}

【讨论】:

  • 当我尝试在控制台日志中显示(访问)它时它是未定义的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-20
  • 1970-01-01
相关资源
最近更新 更多