如何在Angularjs中将字符串转换为对象
问题描述:
我有一个字符串:
$scope.text = '"{\"firstName\":\"John\",\"age\":454 }"';
我希望转换为js对象:
and I want to convert to js object:
$scope.tmp = {"firstName":"John","age":454 };
注意:
JSON.parse()
不起作用!!
这是 codepen
答
你可以用 angular.fromJson()
在你的样本中,它应该是 $ scope.tmp = angular.fromJson($ scope.text);
in your sample, it would have been $scope.tmp = angular.fromJson($scope.text);
JSON.Parse()
和 angular.fromJson
之间的区别是,angular会检查到确保提供了一个字符串。如果它已经是一个对象,它将返回相同的对象。
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.