在 AngularJS 中解析 JSON 字符串 - 给出未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23106334/
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-09-03 17:16:24 来源:igfitidea点击:
Parsing JSON String in AngularJS - Gives undefined
提问by iCode
Hi I have a code like following in my controller
嗨,我的控制器中有如下代码
myClientApp.controller('ListCtrl', function ($scope,$http,$cookieStore,$location, $routeParams) {
var data = {
"menus": {
"view": true,
"add": true,
"update": true,
"delete": true
},
"linkInfo": {
"labelColumn": "codeName",
"linkColumn": "lookupKey",
"urlInfo": "reference"
},
"resultList": [
"{\"lookupKey\":2,\"clientKey\":1,\"codeName\":\"Application.AppType\",\"codeValue\":\"ApplicationType2\",\"codeDesc\":\"##\",\"updatedBy\":null,\"internalCodeName\":\"Application.AppType\"}",
"{\"lookupKey\":3,\"clientKey\":1,\"codeName\":\"Application.Class\",\"codeValue\":\"Tier 1\",\"codeDesc\":\"Critical Application requiring immediate response in case of a disruption of Service\",\"updatedBy\":null,\"internalCodeName\":\"Application.Class\"}"
]
};
$scope.result = angular.fromJson(data.resultList);
alert($scope.result[0].codeName);
});
And It gives me undefined. Why?
它给了我undefined。为什么?
回答by mingos
Because resultListis an array of JSON strings, not a single JSON string; you need to specify which key you want to decode:
因为resultList是一个 JSON 字符串数组,而不是单个 JSON 字符串;您需要指定要解码的密钥:
$scope.result = [
angular.fromJson(data.resultList[0]),
angular.fromJson(data.resultList[1])
];
alert($scope.result[0].codeName);

