Javascript 如何在Angularjs中将字符串转换为对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38180525/
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 21:10:03  来源:igfitidea点击:

How to convert string to object in Angularjs

javascriptangularjsjsonobjectconverter

提问by Ehsan Ali

I have a string like :

我有一个像这样的字符串:

$scope.text = '"{\"firstName\":\"John\",\"age\":454 }"';

and I want to convert to js object:

我想转换为 js 对象:

 $scope.tmp =  {"firstName":"John","age":454 };

Note: JSON.parse()doesn't work!!

It's my sample in codepen

注意:JSON.parse()不起作用!!

这是我在codepen 中的示例

回答by Deblaton Jean-Philippe

You can do it with angular.fromJson()

你可以用angular.fromJson()

in your sample, it would have been $scope.tmp = angular.fromJson($scope.text);

在你的样本中,它本来是 $scope.tmp = angular.fromJson($scope.text);

The difference between JSON.Parse()and angular.fromJson, is that angular will check to make sure a string is provided. If it is already an object, it will return the same object.

JSON.Parse()angular.fromJson,之间的区别在于angular 将检查以确保提供了一个字符串。如果它已经是一个对象,它将返回相同的对象。