ansman/kotshi

Ordered keys

Closed this issue · 2 comments

When serializing it would be more consistent to use the same key order instead of an essentially random order when writing json objects. e.g. instead of:

{
  "bField": "string",
  "cField": [ 2.0, 3.0 ]
  "aField": 5,
}

always write:

{
  "aField": 5,
  "bField": "string",
  "cField": [ 2.0, 3.0 ]
}

Important note

As we all very well know, JSON objects are "an unordered set of name/value pairs" and so if an implementation requires a certain ordering it is out of spec with regard to JSON.

That said, we also know that in practice, key order can cause subtle yet important differences. For example random ordering affects the hash of a file, can invalidate expected canned string data during tests, etc. For this reason Python's json module has sort_keys, Jackson supports ORDER_MAP_ENTRIES_BY_KEYS, and other libraries have similar features.

So it does not seem unreasonable for Kotshi to generate consistent ordering for the same set of named fields, even if the JSON spec does not require it.

Currently we use the same ordering as they are declared in the primary constructor so it's not random, one might argue for them to be sorted but I think what we have right now make sense too.

Actually that probably makes more sense. If we were talking to a non-compliant JSON interpreter that demanded a certain order we could conform to its requirements. So I agree :)