A look at native JSON support in ECMA5
A few weeks ago I started a series of posts on what we as JavaScript developers took delivery of with ECMA5. I recently gave a talk on the native support for JSON that arrived as part of ECMA5, and that's what I'll be looking at today.
Previously, of course, handling JSON data meant using something like jQuery or the JSON.org library. But JSON has grown hugely as a serious means of serialised data transfer that native support for it in JavaScript was very much necessary.
ECMA5 defines an object of the global scope, JSON. It comes with two rather predictable methods: parse() and stringify().
JSON.parse()
By far the simplest of the two is parse(), which, as its name suggests, parses a wel-formatted string of JSON data into a usable, traversable JavaScript object.
1var str = '{"foo": ["bar", "baz"]}',
2 obj = JSON.parse(str);
3console.log(obj.foo[1]); //baz
So far, so simple.
JSON.stringify()
Things get interesting with the second method, stringify(), however. This does the reverse operation: a JavaScript object is turned into a JSON string.
1var obj = {foo: ["bar", "baz"]},
2 str = JSON.stringify(obj);
3console.log(typeof str); //string
Remember JSON is derived from but not synonymous with JavaScript objects, and as such cannot accommodate certain data types. When stringifying your objects, note that any values that are not strings, numbers, booleans, null, arrays or objects, will be cast either to strings, nulls or, in the case of REGEXP objects, objects.
1var obj = [undefined, function(){}, new Date(), new RegExp()],
2 str = JSON.stringify(obj);
3console.log(str); //[null,null,"2012-05-18T21:39:58.333Z",{}]
A point worth making is that this method, perhaps more than any other, marks JavaSript's move away from its foundings as a rather limited, sober API.
For one, the advent of methods whose names have the "-ify" suffix is a clear sign of influence of third-party libraries. (Ten years ago, this method would have been called toString()).
Secondly, its optional second and third arguments are somewhat bizarre.
Replacer functions
The second argument to stringify() is a function or array which controls how and if a piece of data from the object makes it to the string.
As a function - called iteratively and recursively on each property - whatever you return, provided it's not undefined, gets through. (Interestingly, only undefined prevents this - no other falsy value.
1//allow only dogs through, no cats
2var obj = [
3 {name: "Fido", type: "dog"},
4 {name: "Flossy", type: "cat"}
5 ],
6 str = JSON.stringify(obj, function(key, val) {
7 if (!val.type || val.type == 'dog') return val;
8 });
So like with any filter or transformer, it's all about what you return. You might even want to tweak the value en-route.
As an array, it acts as a simple whitelist of properties names - not of values.
1//keep only animal names - not interested in type
2str = JSON.stringify(obj, ['name']);
3console.log(str);
There's a couple of things to note when using replacers. Firstly, remember the replacer is called recursively - and where your replacer is a function, this means starting with the object itself. I've known this catch people out who expect it to begin from within.
In other words, the first thing passed to the replacer is the object itself, so you will need to return a value for it.
1var obj = [
2 {name: "Fido", type: "dog"},
3 {name: "Flossy", type: "cat"}
4 ],
5 str = JSON.stringify(obj, function(key, val) {
6 if (val.type == 'dog') return val;
7 });
8console.log(str); //undefined
There we wrongly assume that the replacer starts work inside the object, i.e. on the first animal object. It doesn't; it starts on the array. Since our replacer allows data through only if it has a type property equal to "dog", our outer array clearly fails that test, so no value is passed through for it.
Recursive also means it will be called on any objects or arrays the replacer returns, whether it is merely passing them on from the source object or has itself created them.
Secondly, you can prevent properties from being transferred to the string only when dealing with objects, not arrays. If you return undefined from your replacer function and your source object is an array, the value will still go through, but arrive as null.
1//attempt to remove the cat
2var obj = ['dog', 'cat'],
3 str = JSON.stringify(obj, function(key, val) {
4 return val != 'cat' ? val : undefined;
5 });
6console.log(str); //["dog", null]
Thirdly and finally, replacers enact some curious data type coercion. Even though JSON is perfectly capable of handling numbers and booleans, if your replacer returns one of these the value will be cast into string form.
1var obj = ['something'],
2 str = JSON.stringify(obj, function() { return true; });
3console.log(str+' ('+typeof str+')'); //"true (string)"
Spacers
The third and final argument JSON.stringify() accepts allows you to indent the outputted string with a given padder.
You can pass either a string or a number. In the case of a string, that string is used as the padding. In the case of a number, that number of white spaces will be used for padding.
For some reason, the length of the padder is limited to ten, so if your string is longer it will be truncated, else if your number is over ten it will be limited to ten.
1var obj = {"foo": ["bar", "baz"]},
2 str = JSON.stringify(obj, null, 6);
3console.log(str);
That outputs in the following format:
1{
2 "foo":[
3 "bar",
4 "baz"
5 ]
6}
The interesting (but obviously necessary) thing here is that passing a spacer means the output is automatically broken into lines. (It would otherwise have been a single line.)
Et voila
While this is all great stuff, I have to confess I'm still a little shocked at the downright convenience of the whole thing. JavaScript developers just aren't used to that from the JS API!
The replacer argument in particular is downright luxurious, to the point of being of questionable necessity. If you really wanted to sanitise the object before turning it into a string (which in itself would surely not happen that often), you could easily do so yourself by making a copy and looping over it, changing it as required.
Don't get me wrong, I'm all for this brave new world of lavish, PHP-esq, rich API. I'm just taking a little while to acclimatise...
Comments (1)
Samson, at 20/05/'12 19:47, said: