Perl数组 - 尝试解析正确数组元素中的引号

时间:2017-02-24 22:08:47

标签: arrays json perl

我在Perl脚本中一直在努力解决这个问题。对于你Perl专家来说可能是一个扣篮,可能应该更容易,但我不能完全解决这个问题。我可能需要拆分它,不确定。

我的数组代码如下。

while ( my $row = $query_handle->fetchrow_hashref('NAME_lc') ){  
    push @query_output, $row; 
    push (@{portfo->{label}},$row->{data},$row->{label}); 
}   

然后我的阵列打印如下:

    print "array here--";
print "[";
foreach (@{portfo->{label}}) {
    #(@{portfo->{label}},$row->{data});
    print "\{\"data\":";
    print "".$_.",";
    print "\"label\":";
    print "\"".$row[1]."\"\},";
}
print "]";
print "\n";

然后我的输出看起来像这样:

[{"data":2943,"label":""},{"data":CDI3,"label":""}, 
{"data":1,"label":""},{"data":COS-COS2,"label":""}, 
{"data":1087,"label":""},{"data":COS1,"label":""},
{"data":5183,"label":""},{"data":COS2,"label":""},
{"data":2731,"label":""},{"data":CULB,"label":""},{"data":1,"label":""},
{"data":EQUIT,"label":""},{"data":4474,"label":""},
{"data":Network,"label":""},]

我正在尝试在标签部分中将引号中的apha-num字符串数组项设置为CDI3,COS1,COS2等。不知怎的,我把它分开了。同时,我确实希望数值留下“数据”名称对。

[{"data":2943,"label":""},{"data":"CDI3","label":""}, 
{"data":1,"label":""},{"data":"COS-COS2","label":""}, 
{"data":1087,"label":""},{"data":"COS1","label":""},
{"data":5183,"label":""},{"data":"COS2","label":""},
{"data":2731,"label":""},{"data":"CULB","label":""},{"data":1,"label":""},
{"data":"EQUIT","label":""},{"data":4474,"label":""},
{"data":"Network","label":""}]

我确信这是一个更简单的解决方案,我正在制作它,但到目前为止还没有运气。任何提示将不胜感激!

谢谢!

1 个答案:

答案 0 :(得分:5)

use JSON::XS qw( encode_json );

my @data;
while ( my $row = $query_handle->fetchrow_hashref('NAME_lc') ) {  
   # If $row->{data} is a number,
   # make sure it's stored as a number
   # so that it gets serialized as a number.
   $row->{data} += 0 if $row->{data} =~ /^\d+\z/;

   push @data, $row;
}

print(encode_json(\@data));

或者

my $data = $query_handle->fetchall_arrayref({ data => 1, label => 1 });
for my $row (@$data) {
   $row->{data} += 0 if $row->{data} =~ /^\d+\z/;
}

print(encode_json($data));

或者,如果您确保字段名称以小写 [1] 返回,

my $data = $query_handle->fetchall_arrayref({});
for my $row (@$data) {
   $row->{data} += 0 if $row->{data} =~ /^\d+\z/;
}

print(encode_json($data));
  1. 可以使用$dbh->{FetchHashKeyName} = 'NAME_lc';AS `label`
  2. 完成此操作