In Perl, how can I distinguish between numeric and string hash values in JSON encoding?

Viewed 469

In the following code, I have a class tied to a hash. In the FETCH function, I am printing the JSON encoding of the key:

package Example::Tie;
use JSON;
my $json = JSON->new();

sub TIEHASH {
    my ($pkg,@list) = @_;
    bless { @list }, $pkg;
}

sub FETCH {
    my ($tied,$key) = @_;
    return $json->encode({key => $key});
}

package Example;

sub new {
    my ($pkg,@list) = @_;
    my $self = {};
    tie %$self, 'Example::Tie', @list;
    bless $self, $pkg;
}

package main;
my $exp = Example->new();
print($exp->{0} . "\n");

I get the following output:

{"key":"0"}

This results in 0 being encoded as a string. Is there a way to encode it into a number instead?

print($exp->{0} . "\n"); # this should print {"key":0}
print($exp->{'0'} . "\n"); # this should print {"key":"0"}
2 Answers
Related