2010-11-22 38 views
0

我想從訪問mysql數據庫的perl腳本輸出JSON。如何在Perl中循環json結果

我該如何循環查看返回並使用JSON模塊將其轉換爲JSON?

當我做這一切我得到的是1回

while($query_handle->fetch()) { 
    $jsonStructure->{event}; 
    $jsonStructure->{event}->{evid} = $evid; 
    $jsonStructure->{event}->{component} = $component; 
    $jsonStructure->{event}->{firstTime} = $firstTime; 
    $jsonStructure->{event}->{lastTime} = $lastTime; 
    $jsonStructure->{event}->{count} = $count; 
    $jsonStructure->{event}->{summary} = $summary; 
    $jsonStructure->{event}->{severity} = $severity; 
} 

基本上我有很多的活動,不知道怎麼說事件[0] ...

謝謝

回答

3

我認爲你正在尋找的是這樣的:

push @{ $jsonStructure->{events} }, { 
    evid => $evid, 
    component => $component, 
    ..., 
}; 

雖然甚至可能是矯枉過正,因爲喲ü也許可以這樣做:

while (my $row = $dbh->fetchrow_hashref) { 
    push @{ $jsonStructure->{events} }, $row; 
} 

如果所有在DB中列名的是一樣的,你在JSON想要的字段名稱,並且希望所有列,或者:

my @keys = qw(evid component firstTime ...); 

while (my $row = $dbh->fetchrow_hashref) { 
    my %hash; 
    @hash{@keys} = @$row{@keys}; 
    push @{ $jsonStructure->{events} }, \%hash; 
} 

如果你只想要一些列,或者:

# DB colname => JSON field name 
my %mapping = (
    event_id => 'evid', 
    component => 'component', 
    first_time => 'firstTime', 
    ..., 
); 

while (my $row = $dbh->fetchrow_hashref) { 
    my %hash; 
    @hash{ values %mapping } = @$row{ keys %mapping }; 
    push @{ $jsonStructure->{events} }, \%hash; 
} 

爲完全任意映射。 Perl的功能和所有這一切。 :)

+0

感謝hobbs,這些都是非常好的例子。 – shaneburgess 2010-11-23 16:44:30