Skip to content

Commit

Permalink
added boolean shortcut support to Mojo::JSON
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Oct 25, 2012
1 parent 9c937cc commit caf582e
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
1 change: 1 addition & 0 deletions Changes
@@ -1,5 +1,6 @@

3.52 2012-10-25
- Added boolean shortcut support to Mojo::JSON.
- Improved documentation.
- Improved tests.

Expand Down
6 changes: 4 additions & 2 deletions lib/Mojo/JSON.pm
Expand Up @@ -277,7 +277,8 @@ sub _encode_values {
return _encode_object($value) if $ref eq 'HASH';

# True or false
return $value ? 'true' : 'false' if $ref eq 'Mojo::JSON::_Bool';
return $$value ? 'true' : 'false' if $ref eq 'SCALAR';
return $value ? 'true' : 'false' if $ref eq 'Mojo::JSON::_Bool';

# Blessed reference with TO_JSON method
if (blessed $value && (my $sub = $value->can('TO_JSON'))) {
Expand Down Expand Up @@ -346,7 +347,8 @@ stringify them if it doesn't exist.
{"foo": "bar"} -> {foo => 'bar'}
Literal names will be translated to and from L<Mojo::JSON> constants or a
similar native Perl value.
similar native Perl value. In addition C<Scalar> references will be used to
generate booleans, based on if their values are true or false.
true -> Mojo::JSON->true
false -> Mojo::JSON->false
Expand Down
16 changes: 15 additions & 1 deletion t/mojo/json.t
Expand Up @@ -10,7 +10,7 @@ use Mojo::Base -strict;

use utf8;

use Test::More tests => 119;
use Test::More tests => 125;

use Mojo::ByteStream 'b';
use Mojo::JSON;
Expand Down Expand Up @@ -267,6 +267,20 @@ $string = $json->encode(
JSONTest->new(something => {just => 'works'}, else => {not => 'working'}));
is_deeply $json->decode($string), {just => 'works'}, 'successful roundtrip';

# Boolean shortcut
is $json->encode({true => \1}), '{"true":true}', 'encode {true => \1}';
is $json->encode({false => \0}), '{"false":false}', 'encode {false => \0}';
$string = 'some true value';
is $json->encode({true => \!!$string}), '{"true":true}',
'encode true boolean from string';
is $json->encode({true => \$string}), '{"true":true}',
'encode true boolean from string';
$string = '';
is $json->encode({false => \!!$string}), '{"false":false}',
'encode false boolean from string';
is $json->encode({false => \$string}), '{"false":false}',
'encode false boolean from string';

# Errors
is $json->decode('["♥"]'), undef, 'wide character in input';
is $json->error, 'Wide character in input', 'right error';
Expand Down

0 comments on commit caf582e

Please sign in to comment.