Barry P
Barry P

Reputation: 91

Perl array - trying to parse quotes in proper array elements

I have been struggling with this for a while in a Perl script I have. Probably a slam dunk for you Perl experts, and probably should be easier, but I can't quite crack the nut on this. I might be needing to split this, not sure.

My array code as is follows.

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

And then my print of the array is as follows:

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

And then my output looks like this:

[{"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":""},]

I am trying to make the apha-num string array items like CDI3, COS1, COS2, etc in quotes, in the label part. Somehow I'm getting it separated. Meanwhile, I do want the numeric values left with the "data" name pair.

[{"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":""}]

I'm sure it's a simpler fix that I'm making it but so far no luck. Any tips would be greatly appreciated!

Thanks!

Upvotes: 1

Views: 114

Answers (1)

ikegami
ikegami

Reputation: 386216

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));

Or

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));

Or if you ensure the fields names are returned as lowercase[1],

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

print(encode_json($data));

  1. This can be done using $dbh->{FetchHashKeyName} = 'NAME_lc'; or AS `label`.

Upvotes: 5

Related Questions