2011-05-16 159 views
1

这是我的代码为什么我得到这个错误?

#!/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; 

和这些行

$json->{"users"} = $json->encode(\%user_result); 
$json->{"owners"} = $json->encode(\%owner_result); 

给出了错误

Not a HASH reference 

为什么我明白了吗?

这怎么解决?

回答

7

一个JSON对象的东西(至少在XS版本,见下文)只是一个标量引用,所以不能对其执行散列引用操作。在实践中,你遇到的大部分Perl对象都是散列引用,但事实并非总是如此。

我不确定你想通过使用JSON编码JSON对象来完成什么。你需要对JSON对象的内部进行编码吗?或者你只需​​要序列化用户和所有者数据?在后一种情况下,您应该使用新的哈希引用来保存该数据并传递给JSON。如果您确实需要JSON对象的编码,那么使用JSON::PP(JSON模块的“纯Perl”变体)可能会有更好的运气,它使用散列引用。

+0

“你应该使用新的散列引用来保存这些数据并传递给JSON”。这正是我想要做的。 =)我该怎么做? – 2011-05-16 16:27:31

+3

'my $ data; \ n $ data - > {users} = $ json-> encode(\%user_result); \ n $ data - > {owners} = $ json-> encode(\%owner_result); \ n $ json_string = to_json($ data);',单程 – mob 2011-05-16 16:34:12

+0

非常感谢!它立即工作=) – 2011-05-16 17:21:39

2

在我看来,$json = $json->utf8;正在用一个标量,$ json-> utf8的结果替换$ json hash ref。

在分配给$ json - > {...}的行之前,使用Data :: Dumper模块中的Dumper来查看内容。

 
use Data::Dumper; 
print Dumper($json); 
+0

然后我得到'$ VAR1 = undef;'也如果我删除utf-8行。 – 2011-05-16 16:31:37

+0

@Sandra Schlichting:我认为你是在错误的地方去做;在'$ json - > {“users”} = $ json-> encode(\%user_result)之前放置'print Dumper($ json);' – ysth 2011-05-16 17:02:21

2

因为在你的情况下$ json是编码器本身,它是对SCALAR的引用。尝试使用不同的变量来保存结果。像

my %json_result = (users => $json->encode(\%user_result), 
        owners => $json->encode(\%owner_result)); 
+0

完成后,我得到'to_json不应该作为method'。 – 2011-05-16 16:26:03

2

你的大问题是$json是JSON编码器对象,而不是要编码的数据结构。你应该制作一个单独的数据结构。

你的另一个问题是,你试图对你的JSON进行双重编码。此代码:

my $data; # I've added this to fix your first bug 
$data->{"users"} = $json->encode(\%user_result); 
$data->{"owners"} = $json->encode(\%owner_result); 

$json_string = to_json($data); 

将创建一个JSON字符串,解码时,会给你两个键的哈希值。每个键的值将是包含JSON编码散列的字符串。每个值都是一个散列值更有意义。

所以,试试这个:

my $json_string = $json->encode({ 
    users => \%user_result, 
    owners => \%owner_result, 
}); 

在这里,我用匿名hashref,因为没有必要向编码名称的哈希值。我们只使用一次。