JSON and Undefined Object Properties

Ran into an interesting case where the JavaScript object coming out of JSON wasn’t the same as the JavaScript object encoded going in.

When are JSON.parse() and JSON.stringify() not inverses of each another?

Here’s when.

In JavaScript it’s possible to define an object that has an undefined property:

var o = {
    a: "Hello",
    b: undefined
};

It’s then possible to iterate over all the objects properties and see the values as well.

for (var p in o) {
    alert( p + ": " + o[p] );
}

This will show “a: Hello” and “b: undefined”.

Now, to JSON-ify the object and reconstitute it back.
o = JSON.parse( JSON.stringify(o) );

Doing the for-loop again will reveal the object now only has the “a” property (the value is still “Hello”).

Try it.

While I get it, I’m not sure I like it. Ideally, I’d like anything coming out of JSON to be the same as anything going into it.

Assume this object:

var me = {
    mySiblingsGender: undefined
};

This is one of those cases where several subtleties rear their head on edge cases.

First, a known value for mySiblingsGender might be male or female. A null would indicate there is no gender, perhaps by a horrible vegetable peeler accident. (Oh my!) But an undefined value indicates there is one, we just don’t know what it is.

Removing the property completely instead conveys that there is no sibling (absence) — something totally different than null (not having any) or undefined (unknown).

While it’s splitting hairs, if not kindling for religious coding wars, it’s useful to know that JSON-out may not always be the same as JSON-in.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.