我正在尝试将 mysql 查询结果输出为 JSON 格式,但很难以我想要的格式输出数组。
我的sql表如下
Array1,Type,Somevalue
Record1,Type1,1
Record1,Type2,2
Record1,Type3,3
Record2,Type1,4
Record3,Type1,5
Record3,Type3,6
我的用于检索 mysql 行并解析为 json 的 perl 代码如下
use DBD::Mysql;
use JSON::XS;
use IO::File;
use warnings;
use Data::Dumper::Names;
use POSIX;
my $json = JSON::XS->new->ascii->pretty->allow_nonref;
my $datasource = "dbi:mysql:database=$dbname;host=$host;port=$port";
#PERL DBI CONNECT
my $dbh =DBI->connect($datasource, $dbusername, $dbpasswd) || die "Could not connect to database: $DBI::errstr";
#PREPARE THE QUERY
my $query1=qq(select * from table);
my $query_handle1 = $dbh->prepare($query1);
#EXECUTE THE QUERY
$query_handle1->execute();
#my variable
my $i;
my @Types = ("Type1","Type2","Type3");
my @Array1 = ("Record1","Record2","Record3","Record4");
my @sql_query_1_Results;
#LOOP THROUGH RESULTS and store results for later processing
while(my $row = $query_handle1->fetchrow_hashref) {
push @sql_query_1_Results, $row;
}
# create data arrays for record we should get 3 arrays with values
for ($i=0;$i<=$#sql_query_1_Results;$i++)
{
push @{$sql_query_1_Results[$i]->{record}},$sql_query_1_Results[$i]->{Some_Value};
}
foreach my $record(@Array1){
$json = encode_json({ 'name' => $record, 'data'=> \@{$record} });
push @chart1_data, $json;
}
#DISCONNECT FROM THE DATABASE
$dbh->disconnect();
#JSON OUTPUT
my $chart1_data_json=encode_json( { chart1 => \@chart1_data } );
print $chart1_data_json;
上面的代码会给我下面的数组
Record1=[1,2,3]
Record2=[4]
Record3=[5,6]
但我想保持类型的顺序,即以下格式
Record1=[1,2,3]
Record2=[4,0,0]
Record3=[5,0,6]