当我尝试通过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 []
Run Code Online (Sandbox Code Playgroud)
所以在我自己的测试中,通过cmd prompt我知道while正在从我的db正确检索数据并正在构建一个哈希,我假设是正确的.
这是我将哈希引用推送到数组而不是哈希本身的事实吗?一旦我正确地构建了这个字符串,我将把它称为html viajquery
谢谢.
JSON期望引用:
print $json = encode_json(\@temp_array) . "\n";
print $json_text = $json->encode(\@temp_array) . "\n";
Run Code Online (Sandbox Code Playgroud)
编辑:除非您启用allow_nonref.
另一个编辑:这行错了 -
my @temp_array =[]; ## should be my @temp_array = ();
Run Code Online (Sandbox Code Playgroud)
并且这一行会覆盖$ json变量:
print $json = encode_json @temp_array . "\n"; ## the next line in your script shouldn't work
Run Code Online (Sandbox Code Playgroud)
上次编辑 - 未经测试:
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";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3788 次 |
| 最近记录: |