2011-05-16 162 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,因爲沒有必要向編碼名稱的哈希值。我們只使用一次。