RSM RSM - 27 days ago 9
Javascript Question

Angular js Parsing Json object

A json object has a key lastLogin. Value of it is a string.

I am trying to print firstName John and Blake

$scope._users = [{
"User": {
"userid": "dummy",
"lastlogin": "{\"employees\":[{\"firstName\":\"John\"}, {\"firstName\":\"Blake\"}]}",
}
}];


FIDDLE

Any help would be appreciated.

Answer

Try like this

View

<div ng-controller="MyCtrl">
    <div ng-repeat="user in _users" ng-init="myInfo=parJson(user.User.lastlogin)">
        <div ng-repeat="emp in myInfo.employees">{{emp.firstName}}</div>
    </div>
</div>

Controller

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.getName = function (user) {
        return "Names";
    };

    $scope._users = [{
        "User": {
            "userid": "dummy",
                "lastlogin": "{\"employees\":[{\"firstName\":\"John\"},                   {\"firstName\":\"Blake\"}]}",
        }
    }];
    $scope.parJson = function (json) {
        return JSON.parse(json);
    }
    //console.log(JSON.parse($scope._users[0].User.lastlogin));
}

DEMO

you can also use angular.fromJson.

Like this

$scope.parJson = function (json) {
   return angular.fromJson(json);
}

DEMO

Comments