Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 571
RSM Avatar asked Jul 09 '15 02:07

RSM


People also ask

How to parse JSON object JavaScript?

Example - Parsing JSONUse the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

What does JSON parse Do angular?

JSON.parse() The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

What is JSON Stringify and JSON parse?

JSON. stringify() takes a JavaScript object and then transforms it into a JSON string. JSON. parse() takes a JSON string and then transforms it into a JavaScript object.

What is the output of JSON parse?

The JSON. parse() method parses a string and returns a JavaScript object. The string has to be written in JSON format.


2 Answers

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

like image 160
Anik Islam Abhi Avatar answered Oct 01 '22 00:10

Anik Islam Abhi


To parse "lastlogin": "{\"employees\":[{\"firstName\":\"John\"}, {\"firstName\":\"Blake\"}]}" data correctly you can use

angular.fromJson(User.lastLogin);

Just make sure that you are giving inner object i.e. lastlogin to the method and it will remove all invalid characters such as \ and " from the json data.

like image 20
Anonymous Avatar answered Oct 01 '22 01:10

Anonymous