Created
March 22, 2012 13:09
-
-
Save throughnothing/2158269 to your computer and use it in GitHub Desktop.
decoding blessed JSON objects using file descriptors =(
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use v5.10; | |
#use JSON -convert_blessed_universally; | |
package MyJSON; | |
use base "JSON::PP"; | |
use overload; | |
use Data::Dumper; | |
use Carp (); | |
use B (); | |
use Scalar::Util 'reftype'; | |
my $JSON; | |
sub my_encode { | |
($JSON ||= __PACKAGE__->new->allow_blessed)->encode(@_); | |
} | |
sub _sort { | |
defined $keysort ? (sort $keysort (keys %{$_[0]})) : keys %{$_[0]}; | |
} | |
sub hash_to_json { | |
my ($self, $obj) = @_; | |
my @res; | |
$self->encode_error("json text or perl structure exceeds maximum nesting level (max_depth set too low?)") | |
if (++$depth > $max_depth); | |
my ($pre, $post) = $indent ? $self->_up_indent() : ('', ''); | |
my $del = ($space_before ? ' ' : '') . ':' . ($space_after ? ' ' : ''); | |
for my $k ( _sort( $obj ) ) { | |
if ( OLD_PERL ) { utf8::decode($k) } # key for Perl 5.6 / be optimized | |
push @res, string_to_json( $self, $k ) | |
. $del | |
. ( $self->object_to_json( $obj->{$k} ) || $self->value_to_json( $obj->{$k} ) ); | |
} | |
--$depth; | |
$self->_down_indent() if ($indent); | |
return '{' . ( @res ? $pre : '' ) . ( @res ? join( ",$pre", @res ) . $post : '' ) . '}'; | |
} | |
1; | |
package Fucked; | |
use File::Temp 'tempfile'; | |
use Moose; | |
has fucked => ( is => 'ro', default => 'You Are' ); | |
has lol => ( | |
is => 'ro', | |
default => sub { | |
my ($fh, $filename) = tempfile; | |
return $fh; | |
}, | |
); | |
1; | |
my $f = Fucked->new; | |
say MyJSON::my_encode( { eff => $f }); | |
#say $json->encode( { eff => %$f } ); | |
#say $json->encode( { eff => $f } ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment