Subject: | JSON doesn't print out blessed references |
Hi,
I'm using JSON 1.00. JSON's objToJson returns undef when asked to print out a bless reference.
Here's a simple script that reproduces this bug:
#!/usr/bin/perl
use strict;
use JSON;
# create two objects that should be printed out
my $var = bless(
{
foo => 'bar',
baz => 'quux'
},
'Some::Class'
);
my $var2 = { foo => 'bar', baz => 'quux' };
my $json = new JSON( pretty => 1, delimiter => 0, autoconv => 0 );
# this prints out nothing!
print "var object1 = " . $json->objToJson($var) . "\n";
# this works fine:
print "var object2 = " . $json->objToJson($var2) . "\n";
I took a look at how Data::Dumper handles this situation. Line 239 of Dumper.pm (version 2.121) has a line something like this:
# match a string like Some::Class=HASH(0x81195c0)
my ( $realpack, $realtype, $id ) =
( overload::StrVal($var) =~ /^(?:(.*)\=)?([^=]*)\(([^\(]*)\)$/ );
I took that line and modified JSON::Converter to work similarly (see attached patch).
There may be other places where this fix is needed. Let me know what you think.
Thanks,
Jay Buffington
--- Converter.pm Fri Nov 18 08:18:18 2005
+++ /usr/local/lib/perl5/site_perl/5.8.3/JSON/Converter.pm Fri Nov 18 08:21:25 2005
@@ -30,10 +30,13 @@
sub toJson {
my ($self, $obj) = @_;
- if(ref($obj) eq 'HASH'){
+ (overload::StrVal($obj) =~ /^(?:(.*)\=)?([^=]*)\(([^\(]*)\)$/);
+ my $realtype = $2;
+
+ if($realtype eq 'HASH'){
return $self->hashToJson($obj);
}
- elsif(ref($obj) eq 'ARRAY'){
+ elsif($realtype eq 'ARRAY'){
return $self->arrayToJson($obj);
}
else{