Mojo-JSON-Any
view release on metacpan or search on metacpan
lib/Mojo/JSON/XS.pm view on Meta::CPAN
use base 'Mojo::Base';
use JSON::XS;
use Mojo::ByteStream 'b';
# Literal names
our $FALSE = JSON::XS::false;
our $TRUE = JSON::XS::true;
# Byte order marks
my $BOM_RE = qr/
(?:
\357\273\277 # UTF-8
|
\377\376\0\0 # UTF-32LE
|
\0\0\376\377 # UTF-32BE
|
\376\377 # UTF-16BE
|
\377\376 # UTF-16LE
lib/Mojo/JSON/XS.pm view on Meta::CPAN
sub decode {
my ($self, $string) = @_;
# Shortcut
return unless $string;
# Cleanup
$self->error(undef);
# Remove BOM
$string =~ s/^$BOM_RE//go;
# Detect and decode unicode
my $encoding = 'UTF-8';
for my $pattern (keys %$UTF_PATTERNS) {
if ($string =~ /^$pattern/) {
$encoding = $UTF_PATTERNS->{$pattern};
last;
}
}
$string = b($string)->decode($encoding)->to_string;
# Decode UTF-16LE
$array = $json->decode(b("\x{feff}[true]")->encode('UTF-16LE'));
#is_deeply($array, [$json->true], 'decode \x{feff}[true]');
is($array->[0], $json->true);
# Decode UTF-16LE with faihu surrogate pair
$array = $json->decode(b("\x{feff}[\"\\ud800\\udf46\"]")->encode('UTF-16LE'));
is_deeply($array, ["\x{10346}"], 'decode \x{feff}[\"\\ud800\\udf46\"]');
# Decode UTF-16LE with faihu surrogate pair and BOM value
$array = $json->decode(
b("\x{feff}[\"\\ud800\\udf46\x{feff}\"]")->encode('UTF-16LE'));
is_deeply($array, ["\x{10346}\x{feff}"],
'decode \x{feff}[\"\\ud800\\udf46\x{feff}\"]');
## Decode UTF-16LE with missing high surrogate
#$array = $json->decode(b("\x{feff}[\"\\ud800\"]")->encode('UTF-16LE'));
#is_deeply($array, ['\ud800'], 'decode \x{feff}[\"\\ud800\"]');
## Decode UTF-16LE with missing low surrogate
# Decode UTF-32LE
$array = $json->decode(b("\x{feff}[true]")->encode('UTF-32LE'));
#is_deeply($array, [$json->true], 'decode \x{feff}[true]');
is($array->[0], $json->true);
# Decode UTF-32BE
$array = $json->decode(b("\x{feff}[true]")->encode('UTF-32BE'));
#is_deeply($array, [$json->true], 'decode \x{feff}[true]');
is($array->[0], $json->true);
# Decode UTF-16LE without BOM
$array = $json->decode(b("[\"\\ud800\\udf46\"]")->encode('UTF-16LE'));
is_deeply($array, ["\x{10346}"], 'decode [\"\\ud800\\udf46\"]');
# Decode UTF-16BE without BOM
$array = $json->decode(b("[\"\\ud800\\udf46\"]")->encode('UTF-16BE'));
is_deeply($array, ["\x{10346}"], 'decode [\"\\ud800\\udf46\"]');
# Decode UTF-32LE without BOM
$array = $json->decode(b("[\"\\ud800\\udf46\"]")->encode('UTF-32LE'));
is_deeply($array, ["\x{10346}"], 'decode [\"\\ud800\\udf46\"]');
# Decode UTF-32BE without BOM
$array = $json->decode(b("[\"\\ud800\\udf46\"]")->encode('UTF-32BE'));
is_deeply($array, ["\x{10346}"], 'decode [\"\\ud800\\udf46\"]');
# Complicated roudtrips
$string = '[null,false,true,"",0,1]';
$array = $json->decode($string);
isa_ok($array, 'ARRAY', 'decode [null,false,true,"",0,1]');
is($json->encode($array), $string, 'reencode');
$array = [undef, 0, 1, '', $json->true, $json->false];
$string = $json->encode($array);
( run in 0.559 second using v1.01-cache-2.11-cpan-e9daa2b36ef )