LearningCpp LearningCpp - 2 months ago 6
Perl Question

Appending and Prepending values by checking a field in JSON string

Below is the json string that has to be parsed

[{"mnemonic":"SIG1039.CA.01","ID":"203024","portList":null},{"mnemonic":"SIG0315.OR.01","ID":"035066","portList":03}


In the above json format
if the portlist is empty then


  1. Create 2 values by appending 03 and 04 and prepend 7802 to ID .


    i.e 780220302403,780220302404

  2. OR if the portlist has an entry just append it and prepend 7802 to ID


    i.e 780203506603



Is the code below correct, I used map to acheive it,but not proper
What would be the correct approach.

use lib '.';
use JSON::PP qw(decode_json);
use File::Find;
use Switch;
use Data::Dumper;
use strict;
open my $my_fh, '<', 'Data.txt' or die $!;
my $data = <$fh_ptoto_wiu>;
my $decoded_data = decode_json $data;
for (@$decoded_data ){
my ($value) = map { $_ eq null ? [7802.$_->{ID}.03,7802.$_->{ID}.04] : 7802.$_->{ID}.$_->{portList} } $_->{portList};
push @myarray,$value;
}

Answer

In order to make this work, I needed to fix the JSON. The 03 in the second portList needs to be quoted because of the leading zero, and the closing ] for the array was missing.

The following program demonstrates how to solve your problem.

use strict;
use warnings;
use JSON 'decode_json';
use Data::Printer;    

my $data         = <DATA>;
my $decoded_data = decode_json $data;

my @myarray;
foreach my $obj (@$decoded_data) {
    my $value;
    if ( $obj->{portList} ) {
        # if the portlist has an entry just append it and prepend 7802 to ID
        $value = [ '7802' . $obj->{ID} . $obj->{portList} ];
    } else {
        # Create 2 values by appending 03 and 04 and prepend 7802 to ID
        $value = [
            '7802' . $obj->{ID} . '03',
            '7802' . $obj->{ID} . '04',
        ];
    }

    push @myarray, $value;
}

p @myarray;

__DATA__
[{"mnemonic":"SIG1039.CA.01","ID":"203024","portList":null},{"mnemonic":"SIG0315.OR.01","ID":"035066","portList":"03"}]

The output looks pretty much like your examples.

[
    [0] [
        [0] 780220302403,
        [1] 780220302404
    ],
    [1] [
        [0] 780203506603
    ]
]

You need to know that a null value will convert to undef when you use the JSON module in Perl. You were doing a string equal eq with the literal null, which just doesn't exist in your program. Just using null will make Perl think it's an unquoted string because there is no function of that name, which is not allowed (because of strict). If you'd quote it, it would still not make sense. It would give an undefined value warning.

Besides that, don't do map if you can do a loop to make stuff more clear.