frank1 has asked for the wisdom of the Perl Monks concerning the following question:

how can i add a [ in my json message to be like this

[ { "id": 1, "location": "UAE", "name": "jake", "gender": "male" } ]

my script below outputs like this without [

{ "id": 1 "location": "UAE" "name": "jake" "gender": "male" }
my %hash; foreach my $result (@$result) { my ($id, $location, $name, $gender) = @$result; %hash = ( "id" => $id, "location" => $location, "name" => $name, " +gender" => $gender); push( @$result, \%hash ); } my $json = encode_json \%hash; print $CGI->header( -type => 'application/json' ),$json;

Replies are listed 'Best First'.
Re: formatting json message
by stevieb (Canon) on May 16, 2024 at 16:12 UTC

    You haven't shown all of your code, but it looks like you are reading an array, then using a global hash to create the data from each row, then pushing the hashes to the existing array, but then you are only writing to JSON the most recent update to the global hash, and not the array. I think you need to do something like this (untested):

    my @updated_data; foreach my $result (@$result) { my ($id, $location, $name, $gender) = @$result; my %hash = ( "id" => $id, "location" => $location, "name" => $name +, "gender" => $gender); push( @updated_data, \%hash ); } my $json = encode_json \@updated_data; print $CGI->header( -type => 'application/json' ),$json;

      Thank you so much, this is wat i wanted