1

cmdプロンプトを介して perl スクリプトを実行しようとすると、json文字列が返されます。[] 他の投稿を読み、データベースを修正しましたがutf8、エラーは引き続き発生します。perl文字列をエンコードする2つの異なる方法を試しましたが、最初は$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 がデータベースからデータを正しく取得し、ハッシュを作成していることを知っています。これは正しいと想定しています。

ハッシュ自体ではなく、ハッシュ参照を配列にプッシュしているという事実ですか? この文字列を正しく作成したら、それを html 経由で呼び出します。jquery

ありがとうございました。

4

1 に答える 1

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";
于 2012-04-24T17:19:31.490 に答える