Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

formatting json message

by frank1 (Scribe)
on May 16, 2024 at 15:29 UTC ( [id://11159499]=perlquestion: print w/replies, xml ) Need Help??

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11159499]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2024-06-14 21:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.