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

How to convert string to object in Angularjs

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

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

我想转换为 js 对象:

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

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

It's my sample in codepen

你可以用 angular.fromJson()

在您的示例中,它应该是 $scope.tmp = angular.fromJson($scope.text);

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