Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to object in Angularjs [duplicate]

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

like image 540
Ehsan Ali Avatar asked Jul 04 '16 08:07

Ehsan Ali


People also ask

How to convert string to object in AngularJS?

Are you looking for how to convert string to json object using angular. fromjson() in angular js app. we will convert string to object using fromjson(). we can easily convert string to javascript object in angular.

How do you turn a string into an object in JavaScript?

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');

How do you turn an object into a string?

Stringify a JavaScript ObjectUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.


1 Answers

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.

like image 179
Deblaton Jean-Philippe Avatar answered Oct 18 '22 15:10

Deblaton Jean-Philippe