Monday, May 21, 2012

perl DBI recipes column array

Below is my sql query output



Company Col1    Col2    Col3
Comp1 1 2 3
Comp2 4 5 6
Comp3 7 8 9


Perl procedure to connect and retrive results



my $query1= qq(select * from database_table);
my $result1 = $dbh->selectall_arrayref($query1, {Slice => {}});

my %result1 =
map { shift @$_, [ @$_ ]}
@{$dbh->selectall_arrayref($query1)};
my @json_output = map { encode_json( { 'name' => $_, 'data'=> $result1{$_} } )
} sort keys %result1 ;
print Dumper %result1;

[{"name":"Comp1","data":[1,2,3]}, {"name":"Comp2","data":[4,5,6]}, {"name":"Comp3","data":[7,8,9]}]


I have been reading http://www.perlmonks.org/?node_id=284436#fetching but i could not figure out how to store columns values as array elements. (As shown below)



    [{"name":"Col1","data":[1,4,7]}, {"name":"col2","data":[2,5,8]}, {"name":"col3","data":[3,6,9]}]


Also, the value fields by default come as "string" in json, any recommendation on how to convert them as numbers?





No comments:

Post a Comment