尝试通过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
谢谢。
答案 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";