Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Relaxed json encoding and decoding
  • Loading branch information
kberov committed Oct 3, 2014
1 parent 7de505b commit 9872b0f
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
34 changes: 33 additions & 1 deletion lib/Mojo/JSON.pm
Expand Up @@ -9,7 +9,8 @@ use Scalar::Util 'blessed';

has 'error';

our @EXPORT_OK = qw(decode_json encode_json j);
our @EXPORT_OK =
qw(decode_javascript decode_json encode_javascript encode_json j);

# Literal names
my $FALSE = bless \(my $false = 0), 'Mojo::JSON::_Bool';
Expand Down Expand Up @@ -39,13 +40,30 @@ sub decode {
return undef;
}

sub decode_javascript {

# Missing input
die "Missing or empty input\n" unless length(my $string = shift);
local $_ = $string;

# Value
my $value = _decode_value();

# Leftover data
_exception('Unexpected data') unless (m/\G[\x20\x09\x0a\x0d]*\z/gc);

return $value;
}

sub decode_json {
my $value;
return eval { $value = _decode(shift); 1 } ? $value : croak _chomp($@);
}

sub encode { encode_json($_[1]) }

sub encode_javascript { _encode_value(shift) }

sub encode_json { Mojo::Util::encode 'UTF-8', _encode_value(shift) }

sub false {$FALSE}
Expand Down Expand Up @@ -347,12 +365,26 @@ escaped to make JSONP easier.
L<Mojo::JSON> implements the following functions, which can be imported
individually.
=head2 decode_javascript
my $value = decode_javascript($string);
Relaxed decoding from JavaScript object to Perl value. Dies if decoding fails.
Decoding from UTF-8 is not performed.
=head2 decode_json
my $value = decode_json($bytes);
Decode JSON to Perl value and die if decoding fails.
=head2 encode_javascript
my $value = encode_javascript({ b => "Б" }); #{"foo": "Б"}
Relaxed encoding from Perl value to JavaScript object.
Encoding to UTF-8 is not performed.
=head2 encode_json
my $bytes = encode_json({foo => 'bar'});
Expand Down
8 changes: 6 additions & 2 deletions t/mojo/json.t
@@ -1,6 +1,5 @@
package JSONTest;
use Mojo::Base -base;

has 'something' => sub { {} };

sub TO_JSON { shift->something }
Expand All @@ -10,7 +9,7 @@ use Mojo::Base -strict;

use Test::More;
use Mojo::ByteStream 'b';
use Mojo::JSON qw(decode_json encode_json j);
use Mojo::JSON qw(decode_json encode_json j decode_javascript encode_javascript);
use Mojo::Util 'encode';
use Scalar::Util 'dualvar';

Expand Down Expand Up @@ -154,6 +153,11 @@ is $bytes, '""', 'encode ""';
$bytes = encode_json "hell\no";
is $bytes, '"hell\no"', 'encode "hell\no"';

my $string = encode_javascript [qw(Здравей Свят!)];
is $string,'["Здравей","Свят!"]', 'encode_javascript works';
my $ref = decode_javascript '["Здравей","Свят!"]';
is_deeply $ref,[qw(Здравей Свят!)], 'decode_javascript works';

# Encode object
$bytes = encode_json {};
is $bytes, '{}', 'encode {}';
Expand Down

0 comments on commit 9872b0f

Please sign in to comment.