in reply to Re: Preserve the order in JSON
in thread Preserve the order in JSON
Anyway, I came up with a good solution for this using Monkey::Patch with JSON::PP to make it use Tie::IxHash for all objects decoded from JSON. This solves the problem, allowing a JSON file to be loaded, decoded from JSON, modified, encoded into JSON again and written back to the file, without changing the key ordering at all. Just make sure you're using JSON::PP (not JSON::XS) and that the $handle variable remains in scope:
use Monkey::Patch qw[patch_package]; # Monkey-patch JSON::PP::object() subroutine to use Tie::IxHash. my $handle = patch_package 'JSON::PP' => 'object' => sub { my $orig = shift; my %obj; tie %obj, 'Tie::IxHash' or die "tie(\%obj, 'Tie::IxHash') failed!\n"; $orig->(\%obj) };
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^3: Preserve the order in JSON
by Discipulus (Canon) on Sep 11, 2023 at 07:35 UTC | |
Re^3: Preserve the order in JSON
by tobyink (Canon) on Sep 11, 2023 at 15:38 UTC | |
Re^3: Preserve the order in JSON
by LanX (Saint) on Sep 11, 2023 at 08:14 UTC | |
by afoken (Chancellor) on Sep 11, 2023 at 14:59 UTC |