www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Reverse JSON toPrettyString

reply Anonymouse <asdf asdf.net> writes:
I have a JSON string[][string] associative array object that I 
want to take the .toPrettyString value of. However, it sorts the 
output alphabetically.

string[][string] aa = [ "abc" : [], "def" : [], "ghi" : [] ];
auto asJSON = JSONValue(aa);
writeln(asJSON.toPrettyString);

Output:

{
     "abc": [],
     "def": [],
     "ghi": []
}

https://run.dlang.io/is/F85azk

Is there a way to .retro the keys in the output so they appear in 
the reverse order?
Dec 17 2018
parent Steven Schveighoffer <schveiguy gmail.com> writes:
On 12/17/18 5:09 PM, Anonymouse wrote:
 I have a JSON string[][string] associative array object that I want to 
 take the .toPrettyString value of. However, it sorts the output 
 alphabetically.
 
 string[][string] aa = [ "abc" : [], "def" : [], "ghi" : [] ];
 auto asJSON = JSONValue(aa);
 writeln(asJSON.toPrettyString);
 
 Output:
 
 {
      "abc": [],
      "def": [],
      "ghi": []
 }
 
 https://run.dlang.io/is/F85azk
 
 Is there a way to .retro the keys in the output so they appear in the 
 reverse order?
Sorting is done here: https://github.com/dlang/phobos/blob/21afd40c422efdb8483d15aa31a867b0cd69fa8b/std/json.d#L1416 I'm not exactly sure why it's sorted, possibly so unittests pass? It doesn't really need to be. But of course, then the order would depend on the hash algorithm. Only way to fix this would be to have a specialized "order-retaining" hash map that JSONValue used, which you could then rearrange as necessary. -Steve
Dec 18 2018