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
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.
Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With