Skip to content

Commit

Permalink
explain what an undef return value means
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Mar 3, 2014
1 parent 8d2fe50 commit 349482b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
11 changes: 7 additions & 4 deletions lib/Mojo/JSON.pm
Expand Up @@ -310,8 +310,9 @@ Mojo::JSON - Minimalistic JSON
# Handle errors
my $json = Mojo::JSON->new;
if (defined(my $hash = $json->decode($bytes))) { say $hash->{message} }
elsif (my $err = $json->error) { say "Error: $err" }
my $hash = $json->decode($bytes);
my $err = $json->error;
say $err ? "Error: $err" : $hash->{message};
=head1 DESCRIPTION
Expand Down Expand Up @@ -369,7 +370,8 @@ Encode Perl value to JSON.
my $value = j($bytes);
Encode Perl data structure (which may only be an C<Array> reference or C<Hash>
reference) to JSON or decode JSON and return C<undef> if decoding fails.
reference) to JSON or decode JSON, an C<undef> return value indicates a bare
C<null> or that decoding failed.
=head1 ATTRIBUTES
Expand All @@ -391,7 +393,8 @@ following new ones.
my $value = $json->decode($bytes);
Decode JSON to Perl value and return C<undef> if decoding fails.
Decode JSON to Perl value, an C<undef> return value indicates a bare C<null>
or that decoding failed.
=head2 encode
Expand Down
15 changes: 8 additions & 7 deletions lib/Mojo/Message.pm
Expand Up @@ -143,7 +143,7 @@ sub is_limit_exceeded { !!shift->{limit} }
sub json {
my ($self, $pointer) = @_;
return undef if $self->content->is_multipart;
my $data = $self->{json} ||= j($self->body);
my $data = $self->{json} //= j($self->body);
return $pointer ? Mojo::JSON::Pointer->new($data)->get($pointer) : $data;
}

Expand Down Expand Up @@ -570,12 +570,13 @@ Check if message has exceeded L</"max_line_size"> or L</"max_message_size">.
my $value = $msg->json;
my $value = $msg->json('/foo/bar');
Decode JSON message body directly using L<Mojo::JSON> if possible, returns
C<undef> otherwise. An optional JSON Pointer can be used to extract a specific
value with L<Mojo::JSON::Pointer>. Note that this method caches all data, so
it should not be called before the entire message body has been received.
The whole message body needs to be loaded into memory to parse it, so you have
to make sure it is not excessively large.
Decode JSON message body directly using L<Mojo::JSON> if possible, an C<undef>
return value indicates a bare C<null> or that decoding failed. An optional
JSON Pointer can be used to extract a specific value with
L<Mojo::JSON::Pointer>. Note that this method caches all data, so it should
not be called before the entire message body has been received. The whole
message body needs to be loaded into memory to parse it, so you have to make
sure it is not excessively large.
# Extract JSON values
say $msg->json->{foo}{bar}[23];
Expand Down

0 comments on commit 349482b

Please sign in to comment.