迭代angularjs中的字符串化json数据返回undefined

时间:2018-05-17 11:22:12

标签: javascript angularjs json

我正在尝试使用angularjs迭代字符串化的json数据,但是在输出变量时我得到了未定义。从控制台中挑选时,我的json格式如下所示

{"data":[
{"id":1,"firstname":"jhfhfh","lastname":"hchch","middlename":null,"dob":"hhc","gender":"hhhhchch","nat":"chhch","phonenumber":null,"idn:"chch",
"email":"yuyu@yahoo.com","username":"cat","password":"password","country":"hshh","state":"hdhdh","city":"hdhdh","address":"area","confirmedEmail":null,"dateOfReg":"hhc"}],
"status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"/up","requestHeaders":{"Accept":"application/json"},
"params":{"email":"yuyu@yahoo.com"},"headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"OK"}

这是我的角度函数

getData: function (email) {
        $http({
            method: 'GET',
            url: '/up',
            requestHeaders: {Accept: 'application/json'},
            params: {email: email}
        }).then(function successCallback(res) {
            if (res.status == 204) {

            } else if (res.status == 200) {

                var myJSON = JSON.stringify(res);

                console.log(myJSON); //prints the data

                var variable = '';
                var name = '';
                angular.forEach(myJSON,function(item) { //attempting to do the iteration here
                    variable +=  item.email ;
                    name +=  item.username ;

                })

                alert(variable); //outputs undefined

            }
        }, function errorCallback(response) {
            alert(JSON.stringify(response));
        });
    }
    }

如何循环浏览json数据

2 个答案:

答案 0 :(得分:1)

你做错了:

getData: function (email) {
    $http({
        method: 'GET',
        url: '/up',
        requestHeaders: {Accept: 'application/json'},
        params: {email: email}
    }).then(function successCallback(res) {
        if (res.status == 204) {

        } else if (res.status == 200) {

            var myJSON = res.data; // <-- THIS IS WHAT I HAVE CHANGED

            console.log(myJSON); //prints the data

            var variable = '';
            var name = '';
            angular.forEach(myJSON,function(item) { //attempting to do the iteration here
                variable +=  item.email ;
                name +=  item.username ;

            })

            alert(variable); //outputs undefined

        }
    }, function errorCallback(response) {
        alert(JSON.stringify(response));
    });
}
}

var myJSON = res.data;,它会起作用。你的res.data是一个数组,所以迭代它。

答案 1 :(得分:0)

将JSON.parse用于解析字符串到JSON对象, 如果你有response.data作为数组,你可以使用native forEach方法