chows2603 chows2603 - 5 months ago 32
AngularJS Question

How can I navigate through this JSON response?

I am a new to JSON and facing problems accessing the following JSON returned by a REST Controller in AngularJS controller as below:

$scope.fetchFormData = function (empId) {
CommonService.fetchform(empId).
then(function(data) {
console.log(JSON.stringify(data.employee));
console.log(JSON.stringify(data.employee['fname']));
console.log(JSON.stringify(data.employee['lname']));
console.log(JSON.stringify(data.employee['location']));

});

}


Service:

fetchform : function(empId) {
var deferred = $q.defer();
return $http.get(applink+'/fetchEmployee/'+empId)
.success(function (data) {})
.then(function(response) {
if (typeof response.data === 'object') {
console.log('fetchEmployee -> Data recieved :'+JSON.stringify(response.data));
deferred.resolve(response.data);
return deferred.promise;
}
else {
// invalid response
console.log('fetchEmployee -> Invalid Data recieved');
return $q.reject(response.data);
}
},function(response) {
// something went wrong
console.log('fetchEmployee -> Something went wrong');
return $q.reject(response.data);
});
}


JSON:

{
"employee": [{
"fname": "John",
"lname": "Doe",
"location": "CA"
}, {
"fname": "Jenny",
"lname": "Doe",
"location": "CA"
}]
}


I want to access the values of
fname
,
lname
, and
location
from the above response.

Answer

Worked using the following:

var values = data;
                var i=0;
                 angular.forEach(values,function(value,index){
                        console.log(' Value 723  '+value);
                        console.log(' Index 724  '+index);
                        i++;
                      angular.forEach(value,function(internalValue,key){

                            console.log('  InternalValue 725  '+JSON.stringify(internalValue));
                        console.log('  Internal Key 726  '+key2);

                      });


                 });
                 console.log(' Ctrl Counter 729  '+i);

Thanks for the suggestions guys. :)