How to convert string to object in Angularjs [duplicate]

匿名 (未验证) 提交于 2019-12-03 08:41:19

问题:

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:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!