Javascript Angular js 解析 Json 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31307084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:31:03  来源:igfitidea点击:

Angular js Parsing Json object

javascriptjsonangularjs

提问by RSM

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

一个 json 对象有一个键 lastLogin。它的值是一个字符串。

I am trying to print firstName Johnand Blake

我正在尝试打印名字JohnBlake

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

FIDDLE

小提琴

Any help would be appreciated.

任何帮助,将不胜感激。

回答by Anik Islam Abhi

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

DEMO

you can also use angular.fromJson.

你也可以使用angular.fromJson.

Like this

像这样

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

DEMO

DEMO

回答by SachiN Ware.

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

"lastlogin": "{\"employees\":[{\"firstName\":\"John\"}, {\"firstName\":\"Blake\"}]}"正确解析数据,您可以使用

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.

只要确保您将内部对象即 lastlogin 提供给该方法,它就会从 json 数据中删除所有无效字符,例如 \ 和 " 。