Skip to content

Commit

Permalink
Make j throw exceptions on invalid JSON
Browse files Browse the repository at this point in the history
  • Loading branch information
marcusramberg committed Mar 22, 2013
1 parent 890c57e commit 3887d86
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
12 changes: 8 additions & 4 deletions lib/Mojo/JSON.pm
Expand Up @@ -5,6 +5,7 @@ use B;
use Exporter 'import';
use Mojo::Util;
use Scalar::Util 'blessed';
use Carp 'croak';

has 'error';

Expand Down Expand Up @@ -104,9 +105,12 @@ sub encode {
sub false {$FALSE}

sub j {
my $d = shift;
return __PACKAGE__->new->encode($d) if ref $d eq 'ARRAY' || ref $d eq 'HASH';
return __PACKAGE__->new->decode($d);
my $d = shift;
my $json = __PACKAGE__->new;
my $res
= ref($d) =~ /^(?:ARRAY|HASH)$/ ? $json->encode($d) : $json->decode($d);
$res // croak($json->error);
return $res;
}

sub true {$TRUE}
Expand Down Expand Up @@ -381,7 +385,7 @@ L<Mojo::JSON> implements the following functions.
my $array = j($bytes);
my $hash = j($bytes);
Encode Perl data structure or decode JSON and return C<undef> if decoding
Encode Perl data structure or decode JSON and die with error if decoding
fails.
=head1 ATTRIBUTES
Expand Down
2 changes: 2 additions & 0 deletions t/mojolicious/ojo.t
Expand Up @@ -40,6 +40,8 @@ is j([1, 2]), '[1,2]', 'right result';
is_deeply j('[1,2]'), [1, 2], 'right structure';
is j({foo => 'bar'}), '{"foo":"bar"}', 'right result';
is_deeply j('{"foo":"bar"}'), {foo => 'bar'}, 'right structure';
eval { j('{') };
like $@, qr/Malformed JSON/, 'JSON exceptions are fatal';

# ByteStream
is b('<foo>')->url_escape, '%3Cfoo%3E', 'right result';
Expand Down

0 comments on commit 3887d86

Please sign in to comment.