Skip to content

Commit

Permalink
Merge pull request #2 from RsrchBoy/topic/encode_json_pretty
Browse files Browse the repository at this point in the history
Add encode_json_pretty for easy prettification of json string output
  • Loading branch information
robinedwards committed Apr 2, 2013
2 parents f1b486a + 9cb6550 commit 576795f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
16 changes: 14 additions & 2 deletions lib/autobox/JSON.pm
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ autobox::JSON - bringing JSON functions to autobox
say {name => 'Jim', age => 34}->encode_json;
# {"name":"Jim","age":46}
my $person = '{"name":"Jim","age":46}'->decode_json
# {name => 'Jim', age => 34}
my $serialized_person = $person->encode_json;
# {"name":"Jim","age":46}
# works on arrays too
[1, 2, 3, 4, 5]->encode_json;
Expand All @@ -41,6 +41,17 @@ autobox::JSON - bringing JSON functions to autobox
This method behaves the same as L<JSON/encode_json>.
=head2 encode_json_pretty
This method is identical to L</encode_json>, except that it also "prettifies"
the output, making it easier for us mortals to read. This is useful
especially when dumping a JSON structure to something reasonable for, say,
debug or other purposes.
It is functionally the same as:
JSON->new->utf8->pretty->encode($ref)
=head2 decode_json
This method behaves the same as L<JSON/decode_json>.
Expand Down Expand Up @@ -88,5 +99,6 @@ package autobox::JSON::Ref;
require JSON;
sub to_json { JSON::to_json(shift); }
sub encode_json { JSON::encode_json(shift); }
sub encode_json_pretty { JSON->new->utf8->pretty->encode(shift); }

1;
9 changes: 8 additions & 1 deletion t/encode-decode.t
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,14 @@ is {name => 'Jim', age => 46}->encode_json, '{"name":"Jim","age":46}', "hash to

my $hash = { name => 'Jim', age => 46};

is $hash->encode_json,, '{"name":"Jim","age":46}', "hash to json";
is $hash->encode_json, '{"name":"Jim","age":46}', "hash to json";

is $hash->encode_json_pretty,
'{
"name" : "Jim",
"age" : 46
}
', "hash to pretty json";

is [1,2,3,4]->encode_json, '[1,2,3,4]', "array to json";

Expand Down

0 comments on commit 576795f

Please sign in to comment.