This is my code
#!/usr/bin/perl -T
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use CGI qw(:standard);
use JSON;
use utf8;
use strict;
use warnings;
# ... ;
my $cgi = CGI->new;
$cgi->charset('UTF-8');
my @owners = map { s/\s*//g; $_ } split ",", $cgi->param('owner');
my @users = map { s/\s*//g; $_ } split ",", $cgi->param('users');
my $json = JSON->new;
$json = $json->utf8;
my %user_result = ();
foreach my $u (@users) {
$user_result{$u} = $db1->{$u}{displayName};
}
my %owner_result = ();
foreach my $o (@owners) {
$owner_result{$o} = $db2{$o};
}
$json->{"users"} = $json->encode(\%user_result);
$json->{"owners"} = $json->encode(\%owner_result);
$json_string = to_json($json);
print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json_string;
and these lines
$json->{"users"} = $json->encode(\%user_result);
$json->{"owners"} = $json->encode(\%owner_result);
gives the error
Not a HASH reference
Why do I get that?
How can that be fixed?
A
JSONobject (at least in the XS version, see below) is just a SCALAR reference, so you can’t perform a hash reference operation on it. In practice, most of the Perl objects you encounter will be hash references, but this will not always be the case.I’m not sure what you are trying to accomplish by using JSON to encode a JSON object. Do you need to encode the internals of the JSON object? Or do you just need to serialize the user and owner data? In the latter case, you should just use a new hash reference to hold that data and pass to JSON. If you really do require an encoding of the JSON object, you might have some better luck using
JSON::PP(the “Pure Perl” variant of the JSON module), which does use a hash reference.