How to convert string to object in Angularjs [dupl

2019-04-20 03:05发布

This question already has an answer here:

I have a string like :

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

and I want to convert to js object:

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

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

It's my sample in codepen

1条回答
Anthone
2楼-- · 2019-04-20 03:16

You can do it with angular.fromJson()

in your sample, it would have been $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.

查看更多
登录 后发表回答