angular.fromJson和$范围。$ EVAL之间的差异时,适用于JSON字符串 [英] Difference between angular.fromJson and $scope.$eval when applied to JSON string
问题描述
在我angularjs的应用程序,我通常用JSON字符串解析 angular.fromJson
,就像这样:
VAR myObject的= angular.fromJSON(jsonString);
不过,看起来,我会使用 $ $范围的eval
获得同样的结果:
VAR myObject的= $ $范围的eval(jsonString);
或使用香草JavaScript中,像这样:
VAR myObject的= JSON.parse(jsonString);
-
有没有使用任何特别的理由
angular.fromJSON
,而不是JSON.parse
? -
是否有任何可能的问题时使用
$范围。$ EVAL
解析一个JSON字符串?
检查出的来源$ C $ C :
函数fromJson(JSON){
返回isString(JSON)
? JSON.parse(JSON)
:JSON;
}
他们只是通过传递给 JSON.parse
。
至于 $ EVAL 该弹到< A HREF =https://github.com/angular/angular.js/blob/master/src/ng/parse.js#L1647> $解析:
// $范围$ EVAL来源:
$ eval:评估函数(表达式,当地人){
返回$解析(表达式)(这一点,当地人);
},
$解析源太长职位,但它本质上是能够将内联(字符串化)对象的真正的对象,因此它是有道理的,在这种情况下,它实际上将转换您的JSON为好。
(我不知道,直到刚才通过解析$源读取。)
有没有使用angular.fromJSON而不是JSON.parse什么特别的原因?
块引用>不,不是真的。虽然他们做检查你要确保你不要双击解析JSON字符串,像这样:
VAR jsonString ='{foo的栏};
VAR JSON = JSON.parse(jsonString); //解析一次就不错:)
JSON.parse(JSON); //解析两次不好:(
使用$作用域时是否有任何可能的问题。$ EVAL解析一个JSON字符串?
块引用>我不这么认为过我的头顶,比你做更多的工作是必要的其他。所以,如果你知道你有JSON,没有理由使用较重的$解析功能。
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);
Or by using vanilla javaScript, like so:
var myObject=JSON.parse(jsonString);
Is there any particular reason to use
angular.fromJSON
rather thanJSON.parse
?Is there any possible issue when using
$scope.$eval
to parse a JSON string?解决方案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.
这篇关于angular.fromJson和$范围。$ EVAL之间的差异时,适用于JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!