Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Formatting JSON the right way

by hippo (Bishop)
on Aug 20, 2014 at 12:08 UTC ( [id://1098105]=note: print w/replies, xml ) Need Help??


in reply to Formatting JSON the right way

It looks to me like your while loop is overwriting the values in your hash at every iteration. It would probably be better to construct an array of hashrefs to store the data instead and then convert that array to your JSON at the end.

Replies are listed 'Best First'.
Re^2: Formatting JSON the right way
by Anonymous Monk on Aug 20, 2014 at 12:26 UTC
    Could you provide any code to illustrate what your are suggesting? Thanks!

      Sure, try this:

      my $returned_data = $data_handle->fetchall_arrayref ({}); # Any other ops here, and then: print $q->header(-type => "application/json", -charset => "utf-8"); my $json = encode_json ($returned_data); print $json;

      Untested (especially with ODBC which I almost never use) but hopefully you get the gist. See DBI for the details of fetchall_arrayref.

        Using a while loop to fetch the data is not recommended? If so, is that how I would push each value into the array?
        while (my $row = $data_handle->fetchrow_hashref()) { push( @{$returned_data{'name'}}, $row->{name} ); push( @{$returned_data{'city'}}, $row->{city} ); push( @{$returned_data{'state'}}, $row->{state} ); }

        Thanks!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (5)
As of 2024-04-19 06:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found