Difference between toJSON() and JSON.Stringify() - javascript

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
Can anyone tell me the difference between both these ways of representing an object in JSON notation. I am just confused whether these to achieve the same or there is a difference.

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.

JSON.stringify() - Any valid JSON representation value can be stringified.
The JSON.stringify(..) utility will automatically omit undefined, function, and symbol values when it comes across them. If such a value is found in an array, that value is replaced by null (so that the array position information isn't altered). If found as a property of an object, that property will simply be excluded.
JSON stringification has the special behavior that if an object value has a toJSON() method defined, this method will be called first to get a value to use for serialization.
toJSON() - to a valid JSON value suitable for stringification.
One example, JSON.stringify() an object with circular reference in it, an error will be thrown. toJSON() can fix it as following.
var o = { };
var a = {
b: 32,
c: o
};
// circular reference
o.d = a;
// JSON.stringify( a ); // an error caused by circular reference
// define toJSON method
a.toJSON = function() {
return { b: this.b };
};
JSON.stringify( a ); // "{"b":32}"

I'm also reading Addy Osmani's Developing backbone.js application, and I have the same question. I figured out by trying his example (the todo list) in the console.
var Todo = Backbone.Model.extend({
defaults:{
title:"",
completed:false
}
});
var todo1 = new Todo();
console.log(todo1.toJSON())
//The console shows
//Object {title: "finish your assignment", completed: false}
console.log(JSON.stringify(todo1))
//The console shows
//{"title":"finish your assignment","completed":false}

Related

Is there a way to prevent JSON.stringify from calling toJSON?

JSON.stringify has a feature to enable objects to define their own serialization by defining a function with the name toJSON.
Here is the excerpt from MDN docs:
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.
Is there a way to override it, so that even if there are toJSON methods attached, it ignores them and does the 'normal' serialization?
Reason: There are some toJson methods, having minor bugs, introduced in my environment due to a JS library. And some of those buggy serialized formats have been accepted and server-side is coded to that format.
So, I am stuck not being able to remove the buggy methods, however I would like to hint JSON.stringify to ignore those methods going forward.
You can override the method:
var fn = JSON.stringify;
JSON.stringify = function (o) {
var tmp, toJSON;
if(o.toJSON){
toJSON = o.toJSON;
o.toJSON = undefined;
}
tmp = fn.apply(this, arguments);
toJSON && (o.toJSON = toJSON);
return tmp;
};
If you null a toJSON property in your object it will get back to default behavior
obj.toJSON = null;
If you don't want to modify your object you can make a copy of it before
var copy = Object.assign({}, obj);
obj.toJSON = null;

What does JSON.stringify() does with functions in an object?

Assuming a Javascript object has a function:
function Foo() {
this.a = 32;
this.bar = function (){
alert("Hello World!");
}
}
How does JSON.stringify() deal with the bar function? Is it just ignored? Is this standard practice? What does JSON converts and doesn't convert into the Json string?
Rem: I don't know why people downvoted my question, it is obvious one should not stringify an object with a function. I was just trying to understand the default behavior.
JSON.stringify simply changes functions passed into null if passed into an array, and does not include the property in at all if in an object. It makes no attempt to replicate the function, not even in string form.
For example, see this:
JSON.stringify([function () {}]); // "[null]"
JSON.stringify({ x: function () {} }); // "{}"
If you attempt to stringify a function itself, it's not a valid JSON value, which means that JSON.stringify can't make a valid JSON string:
JSON.stringify(function () {}); // undefined
This is specified as part of the ECMAScript specification, though the actual wording of it is rather complex. However, a note is included that summarises this:
NOTE 5
Values that do not have a JSON representation (such as
undefined and functions) do not produce a String. Instead they produce the undefined value. In arrays these values are represented as
the String null. In objects an unrepresentable value causes the
property to be excluded from stringification.

Is there a way of specifying what data of an object is passed to the serializer when it's being serialized?

I'm serializing quite complex data-structures using native JSON.stringify of chrome(will switch to some serialization library later for cross-browser support). Most of the data can be looked upon as static, but some is dynamic.
When constructing the data I'd like to be able to do something like
var dynamicString=new String();
{a:"foo", b:dynamicString}
Then set the primitive string-value of dynamicString later on. I'd like to do this rather than changing the property "b" of that object because this would allow for constructing this data a lot easier.
I.e. something like:
I've already found out the primitive value of a String-object can't be changed. I've also found out that the valueOf-function can be set to a custom function, and by returning the desired value in that function this can basically be achieved if doing things like:
var dynamicString=new String("bar");
a.valueOf=function(){return ("foo")};
alert (a+"bar");//foobar
The problem is that the serialization apparently doesn't use the valueOf-function. Serializing the dynamicString-object in this case puts "bar" in the string returned by JSON.stringify, rather than "foo" which is desired.
One way of getting what I'm after is recursively looping though all the objects of the data-structure prior to serialization, and replacing dynamicData-objects by the primitive value they return. But I'd like to avoid that if possible.
Any suggestions?
Edit: I could of course also put an object in the data, which I also have a reference to. Then I can set the data of that object "dynamically", which will be reflected in the result-string. But that adds another level in the structure. I just want a string, not an object with a string-property.
I've also found out that the valueOf-function can be set to a custom function, and by returning the desired value in that function this can basically be achieved if doing things like:
var a = new String("bar");
a.valueOf = function(){return ("foo")};
console.log(a+"bar"); // "foobar"
Yet, if you overwrite valueOf it does not make any sense to use a String object (with some different internal value). Use a plain object with a valueOf function, or even with just a property which is changed dynamically. With your current approach, you're getting
console.log(a.concat("bar")); // "barbar"!
The problem is that the serialization apparently doesn't use the valueOf-function. Serializing the dynamicString-object in this case puts "bar" in the string returned by JSON.stringify, rather than "foo" which is desired.
Yes. JSON.stringify does call the toJSON method on objects, which in your case still returns the internal value. If you overwrite that, it will work:
a.toJSON = a.valueOf;
console.log(JSON.stringify(a)); // '"foo"'
As said above, using native String objects doesn't make much sense. Instead, we should create an extra constructor for them:
function DynamicString(value) {
if (!(this instanceof DynamicString))
return new DynamicString(value);
this.set(value);
}
var p = DynamicString.prototype = Object.create(String.prototype, {
constructor: {value: DynamicString, configurable: true}
});
p.set = function(value) {
this.__value__ = String(value);
};
p.valueOf = p.toString = p.toJSON = function() {
return this.__value__;
};
Now, using it:
var a = new DynamicString("foo");
console.log(a+"bar"); // "foobar"
console.log(JSON.stringify({a:a, b:"bar"})); // '{"a":"foo","b":"bar"}'
You even got all the String.prototype methods on it (yet they will yield primitive strings, not dynamic ones).
Use the 2nd parameter to JSON.stringify: replacer
You can also use the toJSON property, it's behaves like a toString.

How to parse or query complex JSON in JavaScript

Is it possible to perform complex queries over a JSON object? I am open to JavaScript or jQuery solutions, the easier the better. I'm envisioning some kind of functional programming language similar to LINQ or SQL.
I Prefer no other third party libraries or add-ons.
UPDATE
From the looks of early answers, an add-on is going to be necessary. In that case, I prefer an add-on that requires no installation process. Something that deploys with the software publish (like jQuery) is fine (e.g. sets of *.js files).
Check out: Is there a query language for JSON?
From that thread:
JaQL(Wiki)
JsonPath.
Json Query
By the time you're interacting with it, it's not a "JSON object," it's a JavaScript object. ("JSON objects" only exist in terms of the data notation.) JavaScript itself doesn't have any advanced functional programming constructs, so you'd need third party libraries for that sort of thing. JavaScript pretty much just has property accessors, an operator for "does this object have a property with this name?" (in, hasOwnProperty), and as of the 5th edition (not yet widely supported), some handy array-specific features like forEach, every, map, filter, and the like.
Use JSON.stringify and a replacer callback to achieve this:
function replacer(match, offset, fullstring)
{
return replacer.str;
}
replacer.str = "\u0022filterValues\u0022:[\u0022hi\u0022,\u0022bye\u0022]"; /* Use DOM node value */
var foo = JSON.stringify({
"Region": {
"filterField": "kw_Region",
"filterValues": [
"aa",
"bb"
]
},
"ApplicationName": {
"filterField": "kw_ApplicationName",
"filterValues": [
"aa",
"bb"
]
},
"IssueType": {
"filterField": "kw_IssueType",
"filterValues": [
"aa",
"bb"
]
},
"Outage": {
"filterField": "kw_Outage",
"filterValues": [
"aa",
"bb"
]
},
"Priority": {
"filterField": "kw_Priority",
"filterValues": [
"aa",
"bb"
]
}
}).replace(/"filterValues[^\]]+./g, replacer)
Here is some documentation on the two JSON methods for serialization and transformation, stringify and parse:
JSON.parse(source, reviver)
This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted.
The reviver is ultimately called with the empty string and the topmost value to permit transformation of the topmost value. Be certain to handle this case properly, usually by returning the provided value, or JSON.parse will return undefined.
if (k === "") return v
JSON.stringify(value, replacer, space)
The stringify method produces a JSON text from a JavaScript value. If value is an object or array, the structure will be visited recursively to determine the serialization of each membr or element. The structure must not be cyclical.
When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the object holding the key.
You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization.
If the replacer parameter is an array, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified.
Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read.
If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces.
var alias = {"Clark":"","phone":""};
function kryptonite(key)
{
var replacement = {};
for(var cursor in this)
{
if(cursor in alias)
replacement[cursor] = this[cursor]
}
return replacement;
}
var contact = {
"Clark":"Kent",
"Kal El":"Superman",
"phone":"555-7777"
}
contact.toJSON = kryptonite;
var foo = JSON.stringify(contact) // "{"Clark":"Kent","phone":"555-7777"}"
References
ECMAScript Wiki:JSON Support
MDN:JSON.parse Examples
MDN:JSON.stringify toJSON behavior
MSDN:toJSON Method
Opera:JSON.parse
hmm... YQL does this sort of thing, but that would be a third party.
you could filter an array with the jQuery $.grep(array,filterfn) method
var newArr = $.grep(oldArr,function(elInArray,index){
return elInArray.key === somevalue;
});
and you can of course use a regexp in there if you wish, or use more complex conditions, such as checking multiple keys, keys within keys, arrays within keys, etc.

Javascript - .toJSON

I am a newbie to JSON & hence I am not sure what $.toJSON(params) means.
Please explain what this does.
It could be this jQuery plugin
var myObj = {};
myObj.propA = "a";
myObj.propB = "b";
myObj.propC = "c";
var jsonString = $.toJSON(myObj); // same as jQuery.toJSON(myObj)
// output: '{ "propA" : "a", "propB" : "b", "propC" : "c" }'
See: http://www.json.org/js.html
A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier.
var myJSONText = JSON.stringify(myObject, replacer);
If the stringify method sees an object that contains a toJSON method, it calls that method, and stringifies the value returned. This allows an object to determine its own JSON representation.
The stringifier method can take an optional array of strings. These strings are used to select the properties that will be included in the JSON text.
The stringifier method can take an optional replacer function. It will be called after the toJSON method (if there is one) on each of the values in the structure. It will be passed each key and value as parameters, and this will be bound to object holding the key. The value returned will be stringified.
So if you have a $.toJSON() method, it could be a badly implemented function to "stringify", or it could be a method that returns the "JSON Representation" of $
It passes the variable params as an argument to the method named toJSON attached to the object stored in the (unhelpfully named) variable $.
Based on the name, it probably converts the contents of the params variable to a String formatted according to the JSON specification.

Categories

Resources