) from #!/usr/bin/perl use JSON::PP...">

Why does this error occur?

I get this error

Argument "\\x{61}" isn't numeric in numeric comparison (<=>) 

from

 #!/usr/bin/perl use JSON::PP; use utf8; use strict; use warnings; use Data::Dumper; my $json = JSON::PP->new->allow_nonref; $json = $json->utf8; my $data = { 12 => { a => 1, b => 2, }, 1 => { x => 3, }, 2 => { z => 4, } }; my $json_string = $json->sort_by(sub { $JSON::PP::a <=> $JSON::PP::b })->encode($data); 

Suppose it encodes a hash into a json string, and then numeric sorts the keys 12 1 2 .

If the problem can be solved using another JSON parser, then this will be fine: =)

What's wrong?

+1
source share
2 answers

If you prefer numerical sorting, but want to return to lexicographic sorting, use this sorting function:

 $json_string = $json->sort_by( sub { $JSON::PP::a <=> $JSON::PP::b || $JSON::PP::a cmp $JSON::PP::b } )->encode($data); 

When the sort keys are not numeric, the numerical comparison operator ( <=> ) will return 0, and the function will perform the lexical comparison operation ( cmp ).


Change (the above solution still did not suppress the warning). To suppress warnings, a few more settings are needed. Could you say

 sub { no warnings 'numeric'; $JSON::PP::a <=> $JSON::PP::b || $JSON::PP::a cmp $JSON::PP::b } 
+9
source

Since aaa bbb a2 not a number, you probably want a lexicographic look.

Try replacing <=> with cmp :

  $json_string = $json->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($data); 
+4
source

All Articles