associative arrays: to sort or not to sort?

Mario Kroeplin kroeplin.d at googlemail.com
Sun Jul 18 13:13:32 PDT 2010


Have a look at the unittest of std.json: the only non-trivial test is commented out as "currently broken".
Smells like std.json has deep problems when it comes to real-world examples.
But then: running the unittest shows that the actual result is {"goodbye":[true,"or",false,["test",42,{"nested":{"a":23.54,"b":0.0012}}]],"hello":{"json":"is
great","array":[12,null,{}]}}.
The two name/value pairs just appear in different order than expected.
That's because "goodbye" < "hello", if you make an illegal assumption for associative arrays, as "the key/value slots are iterated in an unspecified
order." [tdpl]

Now the question:

Shall the "currently broken" unittest be "fixed" by expecting the actual result, with just the order of "goodbye" and "hello" changed?
That is, shall we silently make the illegal assumption, that foreach provides the keys in sorted order.
Or, shall the foreach (key, value; aa) be replaced with a more clumsy foreach (key; aa.keys.sort)?
That is, shall we produce "canonical" JSON text at the price of efficiency.
Or, shall the perfect implementation of JSON objects as associative arrays be dropped?
Or, what else?

By the way: the example before the "currently broken" one is {"a":1,"b":null}; also broken in theory, but not (yet) in practice!


More information about the Digitalmars-d-learn mailing list