【问题标题】:JSON returning NULL in PerlJSON在Perl中返回NULL
【发布时间】:2012-04-25 01:58:28
【问题描述】:

尝试通过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

谢谢。

【问题讨论】:

    标签: json perl


    【解决方案1】:

    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";
    

    【讨论】:

    • 谢谢。确实发现您的“未经测试”代码示例存在问题:print encode_json \@temp_array . "\n"; 仍然给我错误 1print $json->encode(\@temp_array) 。 "\n";` 输出完全符合我的期望!!谢谢!!!!
    • 谢谢。我删除了这条线。我怀疑我应该在该行添加()
    猜你喜欢
    • 2017-02-27
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 2015-01-21
    • 2015-11-27
    • 2017-03-12
    相关资源
    最近更新 更多