Skip to content

Commit

Permalink
fixed small decoding error bug in Mojo::JSON
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Feb 18, 2014
1 parent 85fe227 commit e025126
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 11 deletions.
1 change: 1 addition & 0 deletions Changes
@@ -1,6 +1,7 @@

4.82 2014-02-19
- Added decode_json and encode_json functions to Mojo::JSON.
- Fixed small decoding error bug in Mojo::JSON.
- Fixed bug in "user_agent_online.t".

4.81 2014-02-15
Expand Down
19 changes: 8 additions & 11 deletions lib/Mojo/JSON.pm
Expand Up @@ -41,23 +41,21 @@ my $UTF_PATTERNS = {
my $WHITESPACE_RE = qr/[\x20\x09\x0a\x0d]*/;

sub decode {
my ($self, $bytes) = @_;
my $self = shift->error(undef);

$self->error(undef);
my $res = eval { decode_json($bytes) };
if (!$res && (my $e = $@)) {
chomp $e;
$self->error($e);
}
my $ref = eval { decode_json(shift) };
return $ref if $ref;

return $res;
chomp(my $e = $@);
$self->error($e);
return undef;
}

sub decode_json {
my $bytes = shift;

# Missing input
die "Missing or empty input\n" unless $bytes;
die "Missing or empty input\n" unless length $bytes;

# Remove BOM
$bytes =~ s/^(?:\357\273\277|\377\376\0\0|\0\0\376\377|\376\377|\377\376)//g;
Expand All @@ -68,10 +66,9 @@ sub decode_json {
# Detect and decode Unicode
my $encoding = 'UTF-8';
$bytes =~ $UTF_PATTERNS->{$_} and $encoding = $_ for keys %$UTF_PATTERNS;
$bytes = Mojo::Util::decode $encoding, $bytes;
local $_ = Mojo::Util::decode $encoding, $bytes;

# Leading whitespace
local $_ = $bytes;
m/\G$WHITESPACE_RE/gc;

# Array
Expand Down
4 changes: 4 additions & 0 deletions t/mojo/json.t
Expand Up @@ -368,6 +368,10 @@ is $json->decode("[\"foo\",\n\"bar\",\n\"bazra\"]lalala"), undef,
is $json->error,
'Malformed JSON: Unexpected data after array at line 3, offset 8',
'right error';
is $json->decode('0'), undef, 'syntax error';
is $json->error,
'Malformed JSON: Expected array or object at line 0, offset 0',
'right error';
is j('{'), undef, 'decoding failed';
eval { decode_json("[\"foo\",\n\"bar\",\n\"bazra\"]lalala") };
like $@, qr/Malformed JSON: Unexpected data after array at line 3, offset 8/,
Expand Down

0 comments on commit e025126

Please sign in to comment.