Tuesday 14 November 2017

javascript - How to convert string to object in Angularjs





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 href="http://codepen.io/essvision/pen/PzjGpQ"
rel="noreferrer">codepen




Answer




You can do it with href="https://docs.angularjs.org/api/ng/function/angular.fromJson"
rel="noreferrer">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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...