Ordered JSON Object

Will Holcomb

26 January 2010

I would like to represent a lightweight ordered graph in javascript object notation. For example, consider this simple HTML tree:

One way of representing it in JSON is:

var html = { head: { title: 'Greeting' },
             body: { p: 'Hello digital world!',
                     p: 'This is hypertext' } } }

This lets me write html.head.title == 'Greeting'. However, the p elements overwrite each other, so the Hello digitial world! string is lost. That could be fixed as:

var html = { head: { title: 'Greeting' },
             body: { p: [ 'Hello digital world!',
                          'This is hypertext' ] } }

Which lets me write html.body.p[0] == 'Hello digital world!'. Unfortunately, JSON objects are unordered, so when iterating, the order may be different than the original.

Apparently, all the browsers return them in order, however.