如何在Angularjs中将字符串转换为对象 [英] How to convert string to object in Angularjs
本文介绍了如何在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
推荐答案
你可以用< a href =https://docs.angularjs.org/api/ng/function/angular.fromJson =noreferrer> 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.
这篇关于如何在Angularjs中将字符串转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文