cquadrini
cquadrini

Reputation: 789

JSON returning NULL in Perl

When trying to run my perl script via cmd prompt my json string is returning [] I have read other posts, and fixed my database to be utf8 and the error still persists. I have tried two didfferent way to encode my perl string the first was $json = encode_json @temp_array which returns this error hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this However, when I use this line $json_text = $json->encode(@temp_array) I just get []

Here is my 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 []

So in my own testing, via the cmd prompt I know the while is retrieving the data from my db correctly and is building a hash, which I am assuming is correct.

Is it the fact I am pushing my hash reference to the array instead of the hash itself? Once I get this string built correctly, I will be calling it to an html via jquery

Thank you.

Upvotes: 1

Views: 4808

Answers (1)

gpojd
gpojd

Reputation: 23065

JSON expects references:

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

Edit: Unless you enable allow_nonref.

Another edit: This line is wrong--

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

and this line overwrites the $json variable:

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

Last edit - untested:

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

Upvotes: 6

Related Questions