javascript - toJSON() 和 JSON.Stringify() 之间的区别

if you need to read or clone all of a model’s data attributes, use its toJSON() method. This method returns a copy of the attributes as an object (not a JSON string despite its name). (When JSON.stringify() is passed an object with a toJSON() method, it stringifies the return value of toJSON() instead of the original object. The examples in the previous section took advantage of this feature when they called JSON.stringify() to log model instances.)

http://addyosmani.github.io/backbone-fundamentals/#backbone-basics

谁能告诉我在 JSON 表示法中 representing an object 这两种方式的区别。我只是很困惑这些是实现相同还是有区别。

最佳答案

来自 fine manual :

toJSON behavior

If an object being stringified has a property named toJSON whose value is a function, then the toJSON method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON method when called will be serialized.

这就是 Backbone 使用 toJSON 的原因。序列化方法并给定一个名为 m 的模型实例,您可以这样说:

var string = JSON.stringify(m);

只从 m 中获取属性,而不是你的服务器不会关心的一堆噪音。

也就是说,主要区别在于 toJSON 生成一个值(数字、 bool 值、对象...),该值被转换为 JSON 字符串,而 JSON.stringify 总是产生一个字符串。

default Backbone toJSON就是这样(对于模型):

return _.clone(this.attributes);

所以 m.toJSON() 为您提供模型属性的 shallow 副本。如果有数组或对象作为属性值,那么您将结束意外的引用共享。请注意 Backbone.Model#clone还有suffers from this problem .

如果您想安全地克隆模型的数据,那么您可以通过 JSON.stringify 发送它,然后通过 JSON.parse 来获取深拷贝:

var data         = JSON.parse(JSON.stringify(model_instance));
var cloned_model = new M(data);

其中 model_instance 是 Backbone 模型 M 的实例。

https://stackoverflow.com/questions/20734894/

相关文章:

json - 如何在 JSONPath 中按字符串过滤?

javascript - 如何使用 Typeahead.js 0.10 一步一步/远程/预取/本地

java - 字段上的 @JsonProperty 注释以及 getter/setter

json - 使用逗号拆分 NSString

json - Swift 4 可解码,直到解码时才知道 key

c# - 使用 Nancy 返回包含有效 Json 的字符串

java - Spring REST多个@RequestBody参数,可能吗?

jquery - 缺少 CORS header 'Access-Control-Allow-Ori

javascript - 即使有循环引用,如何将 DOM 节点序列化为 JSON?

json - JSON 表示中的链接关系