in reply to Re^2: Outputting JSON with sorted names/keys (Updated)
in thread Outputting JSON with sorted names/keys

Rest assured: JSON::XS supports the same feature.

Interesting. Since you resurrected this thread, my curiosity has been piqued, and I couldn't remember whether I'd tried to do the same with JSON::XS three years ago or not.

Searching through the JSON::XS codebase finds 0 instances of sort_by , so I am not sure what line of code in the source of JSON::XS could be implementing that function (though maybe there's an inheritance in the XS source, because I'm not sure what the equivalent of use/require/parent/base/@ISA are in XS). Because of that uncertainty, I took the working code that LanX had posted three years ago, and changed every instance of JSON::PP to JSON::XS . When I ran that, I got the message sort_by is not supported by JSON::XS. at C:\....\11111902.pl line 32. and the is() test failed, because the $lanx version was not sorted. Based on that experiment, I cannot see how to use sort_by with JSON::XS in an equivalent manner to how it's used with JSON::PP.

Could you show an example of JSON::XS using sort_by (using the same data and structure as in the working example that LanX posted earlier)? And if it's just called something other than sort_by in the JSON::XS version, please let me know what the right name is (and whether or not it's documented in JSON::XS's POD). Because if it is possible, I'd like to see how. Thanks.

Replies are listed 'Best First'.
Re^4: Outputting JSON with sorted names/keys (Updated)
by bart (Canon) on Jun 20, 2023 at 16:35 UTC
    I found this thread through Google because I recently had this problem.

    When I looked in the docs of JSON::XS I found pretty much the the same paragraph as in the docs of JSON::PP

    $json = $json->canonical ($enable)
    $enabled = $json->get_canonical
    If $enable is true (or missing), then the encode method will output JSON objects by sorting their keys. This is adding a comparatively high overhead.

    Use of canonical fixed my problem... and it will work in both.

      Use of canonical fixed my problem

      I'm glad that the alphanumeric sort of canonical worked for you. However, use of canonical is not sufficient for the original problem that I asked: I didn't just want it sorted; I wanted it sorted in a non-traditional sort order (that is, in an order that I defined). So canonical sort is possible in both, but the arbitrary sort_by mechanism is only available in JSON::PP .