How to convert string to object in Angularjs

63,619

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.

Share:
63,619
Ehsan Ali
Author by

Ehsan Ali

I am learn angular-js

Updated on July 04, 2020

Comments

  • Ehsan Ali
    Ehsan Ali almost 4 years

    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

  • Ehsan Ali
    Ehsan Ali almost 8 years
    please check your answer in my [codepen.io/essvision/pen/PzjGpQ]
  • Deblaton Jean-Philippe
    Deblaton Jean-Philippe almost 8 years
    You have to remove your simple quotes around your string to make it work : $scope.text = "{\"firstName\":\"John\",\"age\":454 }";
  • Moses Ndeda
    Moses Ndeda over 6 years
    Worked like magic!