Property Iteration in JSON serialization

Brian Kardell bkardell at gmail.com
Tue Oct 13 21:24:55 PDT 2009


Because the serialized form (json text) and the native source form (a
specific subset of object literals) are essentially the same, I have
occasionally heard people "in the wild" refer to both literals
themselves and instances of an object parsed from json text as "json".
 Clearly the two are different things which leads me to my question:
With new built in json supports one can serialize an instance of an
object as json text and provide some serialization criteria (a
whilelist or a replacer function) - on the other end easily
de-serialize that back into instance. Great!  One of the great things
about json is that it's quite a readable format and, as Doug Crockford
points out, expresses things in ways that they are naturally thought
about in most modern (especially C-family) languages - so it's very
easy to parse from a machine point of view too and get right to a
useful instance instead of some DOM tree of string values.

So - keeping in mind that the instance and the serialization are
separate things - what if I would like to order my serialization keys
(property names) in natural order?  It has no impact on the parsing or
internal representation, but imposing a known order on the
serialization, even a trivial one, makes things easier to find and
documentation easier to understand.  We've implemented this in a few
local serializers in multiple languages and, since during
serialization we are writing them out by iterating the keys, it's
actually quite trivial to merely call sort() on the keys before
iteration.  Likewise, since this only has to be done once per type -
not once per instance, there is very, very minimal overhead (you are
generally sorting less than 20 keys regardless of the number of
instances).

There are potentially some additional practical upshots beyond human
readability to this which I won't get into here until I find out:  Is
it even plausible to accomplish this with new built in JSON supports?

To be specific, if it's not clear... Given an instance of an order
object, I would like to serialize it like this:

{
    "items": [
        {
            "description": "A bottle of rum",
            "itemId":  13523,
            "price": 12.94,
            "quantity": 6
        },
        {
            "description": "A bottle of whiskey",
            "itemId":  23423,
            "price": 6.95,
            "quantity": 24
        }
    ],
    "orderNumber": 1234123,
    "shipTo": {
        "city": "Seattle",
        "name": "Jane Doe",
        "state": "Washington",
        "streetAddress": "123 Main Street",
        "zip": 12345
    }
}


More information about the es-discuss mailing list