October 21, 2024
https://issues.dlang.org/show_bug.cgi?id=24823

          Issue ID: 24823
           Summary: std.json: Allow optionally preserving the order of
                    fields in JSON objects
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: phobos
          Assignee: nobody@puremagic.com
          Reporter: dlang-bugzilla@thecybershadow.net

The ordering of object members in JSON is explicitly undefined. Therefore, {"a": 1, "b": 2} and {"b": 2, "a": 1} are the same object.

Nevertheless, it is occasionally useful to control and preserve the order in which fields appear in JSON files. The most straight forward example is readability: sometimes, a JSON document is more readable than its equivalent document where its keys have been sorted e.g. alphabetically, as computers may not know that it makes sense to leave a "start_date" member right before the "end_date" member.

Since we already include the option to produce pretty-printed output, which is similarly not required by any specification but aids readability, such an enhancement would not be a major deviation from the current std.json feature set. Furthermore, the ability to preserve JSON field order would bring us closer to parity with other implementations, not least being current implementations of JavaScript itself, which preserves Object key order.

It should be possible, via an optional and backwards-compatible way, to request from std.json that it preserves the order of object fields in memory and during deserialization, and to obey it in such situations during serialization.

--