Reverse JSON toPrettyString

Steven Schveighoffer schveiguy at gmail.com
Tue Dec 18 14:02:07 UTC 2018


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


More information about the Digitalmars-d-learn mailing list