Skip to content

Instantly share code, notes, and snippets.

@moznion
Forked from hisaichi5518/JSON.pm
Created March 18, 2014 09:39
Show Gist options
  • Save moznion/9616736 to your computer and use it in GitHub Desktop.
Save moznion/9616736 to your computer and use it in GitHub Desktop.
package HTTP::Body::JSON;
use strict;
use warnings;
use parent qw(HTTP::Body);
use JSON::XS;
use HTTP::Body;
use Encode qw(encode_utf8);
# based on tokuhirom-san's code
$HTTP::Body::TYPES->{'application/json'} = __PACKAGE__;
sub spin {
my $self = shift;
return unless $self->length == $self->content_length;
my $dat = JSON::XS::decode_json($self->{buffer});
while (my ($k, $v) = each %$dat) {
$self->param(_encode($k), _encode($v));
}
$self->{buffer} = '';
$self->{state} = 'done';
}
sub _encode {
my ($data) = @_;
if (ref $data eq "ARRAY") {
my @result;
for my $d (@$data) {
push @result, _encode($d);
}
return \@result;
}
elsif (ref $data eq "HASH") {
my %result;
while (my ($k, $v) = each %$data) {
$result{_encode($k)} = _encode($v);
}
return \%result;
}
return encode_utf8($data)
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment