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!