In my angularjs apps, I usually parse a JSON string by using angular.fromJson
, like so:
var myObject=angular.fromJSON(jsonString);
The above answer is almost correct. However, there is a potential issue with using $scope.$eval()
to parse a JSON string, which does not exist with either JSON.parse()
or angular.fromJson()
: security. Angular allows an expression to contain complex JavaScript including function calls, conditionals with ?:
, variable assignments, and so on. All of these are recognised and processed if you use $scope.$eval()
, even if they were added by a malicious end-user.
JSON does not support any of those more complex JavaScript features, nor anything else potentially "dangerous". If you use a true JSON parser like JSON.parse()
or angular.fromJson()
, there is no chance of malicious code being injected and executed.
Since Angular expressions are isolated and evaluate only in the current $scope
, the risk of code injection is somewhat mitigated - $scope.$eval()
is far less dangerous than JavaScript's native eval()
for parsing JSON. However there is still no reason to use either function for this purpose, since there is a potential security risk and using a proper JSON parser is likely to be faster.