16

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

4
  • JSON.parse() is what I think you're looking for. - Also, this is a duplicate. Commented Jul 4, 2016 at 8:57
  • This is not an exact duplicate. OP asks for the best answer within its framework (angular). I know JSON.Parse() works, but there is something else to do it with angular, for some reasons. Commented Jul 4, 2016 at 9:06
  • @evolutionxbox, JSON.parse() doesn't work Commented Jul 4, 2016 at 9:26
  • 1
    This is due to the extra quotes. Take off the outer single quotes, and then JSON.parse will work. Commented Jul 4, 2016 at 10:30

1 Answer 1

24

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.

Sign up to request clarification or add additional context in comments.

3 Comments

please check your answer in my [codepen.io/essvision/pen/PzjGpQ]
You have to remove your simple quotes around your string to make it work : $scope.text = "{\"firstName\":\"John\",\"age\":454 }";
Worked like magic!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.