jsonfmt: Add canonical option

Not as bad as I had expected it to be; managed to keep the
implementation a little bit simpler and cleaner than JSON::XS.
This commit is contained in:
Yorhel 2025-01-29 18:42:27 +01:00
parent 163a60b4ba
commit 1a0fb03205
5 changed files with 115 additions and 23 deletions

View file

@ -44,7 +44,7 @@ my @tests = (
{}, '{}',
{'a',1}, '{"a":1}',
do { tie my %h, 'Tie::StdHash'; %h = ('a',1); \%h }, '{"a":1}',
do { tie my %h, 'Tie::StdHash'; %h = ('b',1); \%h }, '{"b":1}',
do { tie my %h, 'MyOrderedHash', one => 1, two => undef, three => []; \%h }, '{"one":1,"two":null,"three":[]}',
do { my $o = [true]; bless \$o, 'MyToJSON' }, '[1,"MyToJSON",[true]]',
@ -68,7 +68,7 @@ my @errors = (
do { my $o = {}; bless $o, 'MyToJSONSelf' }, qr/MyToJSONSelf::TO_JSON method returned same object as was passed instead of a new one/,
);
plan tests => @tests*2 + @errors/2 + 8;
plan tests => @tests*2 + @errors/2 + 9;
for my($in, $exp) (@tests) {
my $out = json_format $in;
@ -87,6 +87,10 @@ for my ($in, $exp) (@errors) {
}
is json_format({qw/a 1 b 2 c 3 d 4 d1 5 d11 6/, do { use utf8; qw/ü 7 月 8 💩 9/ }}, canonical => 1),
do { use utf8; '{"a":"1","b":"2","c":"3","d":"4","d1":"5","d11":"6","ü":"7","月":"8","💩":"9"}' };
eval { json_format [[]], max_depth => 2 };
like $@, qr/max_depth exceeded while formatting JSON/;