Difference between toJSON() and JSON.Stringify()

From the 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.

This is why Backbone uses the toJSON method for serialization and given a model instance called m, you can say things like:

var string = JSON.stringify(m);

and get just the attributes out of m rather than a bunch of noise that your server won’t care about.

That said, the main difference is that toJSON produces a value (a number, boolean, object, …) that gets converted to a JSON string whereas JSON.stringify always produces a string.

The default Backbone toJSON is simply this (for models):

return _.clone(this.attributes);

so m.toJSON() gives you a shallow copy of the model’s attributes. If there are arrays or objects as attribute values then you will end unexpected reference sharing. Note that Backbone.Model#clone also suffers from this problem.

If you want to safely clone a model’s data then you could send it through JSON.stringify and then JSON.parse to get a deep copy:

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

where model_instance is your instance of the Backbone model M.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)