Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

javascript - Difference between angular.fromJson and $scope.$eval when applied to JSON string

In my angularjs apps, I usually parse a JSON string by using angular.fromJson, like so:

var myObject=angular.fromJSON(jsonString);

However, it seems that I would obtain the same result by using $scope.$eval:

var myObject=$scope.$eval(jsonString);

See this fiddle

Or by using vanilla javaScript, like so:

var myObject=JSON.parse(jsonString);
  • Is there any particular reason to use angular.fromJSON rather than JSON.parse?

  • Is there any possible issue when using $scope.$eval to parse a JSON string?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Check out the source code:

function fromJson(json) {
  return isString(json)
      ? JSON.parse(json)
      : json;
}

They're just passing through to JSON.parse.

As for $eval it shells out to $parse:

  // $scope.$eval source:
  $eval: function(expr, locals) {
    return $parse(expr)(this, locals);
  },

$parse source is too long to post, but it is essentially capable of converting inline (stringified) objects to real Objects and so it makes sense that in this case, it will actually convert your JSON as well.

(I did not know this until reading through the $parse source just now.)

Is there any particular reason to use angular.fromJSON rather than JSON.parse?

Nope, not really. Although they do check to you to ensure that you don't double-parse a JSON string, like so:

var jsonString = '{"foo":"bar"}';
var json = JSON.parse(jsonString); // Parsing once is good :)
JSON.parse(json); // Parsing twice is bad :(

Is there any possible issue when using $scope.$eval to parse a JSON string?

I don't think so off the top of my head, other than that you're doing more work than is necessary. So if you know you have JSON, there's no reason to use the heavier $parse function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...