JSON在Perl中返回NULL

时间:2012-04-24 17:16:58

标签: json perl

尝试通过cmd提示运行我的perl脚本时,json字符串返回[]我已阅读其他帖子,并将我的数据库修复为utf8和错误仍然存​​在。我已经尝试了两种不同的方式来编码我的perl字符串,第一个是$json = encode_json @temp_array,它返回此错误hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this但是,当我使用此行$json_text = $json->encode(@temp_array)时,我只得到[]

这是我的perl:

my $json_text;
my $json = JSON->new->utf8;
my @temp_array =[];
my $temp_array;
while (@data = $query_handle->fetchrow_array()) 
    {
    my %json_hash = ();
    my $hash_ref;
    %json_hash = (
                "User ID" => $data[0],
                "Status" => $data[1],
                "Last Password Reset" => $data[2],
                "Reset Needed" => $data[3]
                );
    $hash_ref = \%json_hash;
    push (@temp_array, $hash_ref);
    }   

print $json = encode_json @temp_array . "\n";   #encode with error
print $json_text = $json->encode(@temp_array) . "\n"; #encode with []
print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json_text; #Prints []

所以在我自己的测试中,通过cmd prompt我知道while正在从我的数据库正确检索数据并正在构建一个哈希,我假设是正确的。

是不是我将哈希引用推送到数组而不是哈希本身?一旦我正确构建了这个字符串,我将通过jquery

将其调用为html

谢谢。

1 个答案:

答案 0 :(得分:6)

JSON需要引用:

print $json = encode_json(\@temp_array) . "\n";   
print $json_text = $json->encode(\@temp_array) . "\n";

编辑:除非您启用allow_nonref

另一个编辑:这一行错了 -

my @temp_array =[]; ## should be my @temp_array = ();

并且此行将覆盖$ json变量:

print $json = encode_json @temp_array . "\n"; ## the next line in your script shouldn't work

上次修改 - 未经测试:

my $json = JSON->new->utf8;
my @temp_array;
while (my @data = $query_handle->fetchrow_array()) {
    my %json_hash = (
            "User ID" => $data[0],
            "Status" => $data[1],
            "Last Password Reset" => $data[2],
            "Reset Needed" => $data[3]
    );
    push (@temp_array, \%json_hash);
}   

print $json->encode(\@temp_array) . "\n";