user2772676
user2772676

Reputation: 23

Want to read JSON file strings (multiple values) in perl

Following is my json file (demo.json)

 [
  {
     "Directory" : "/opt/gehc/abc/root/mr_csd/xxx/diag/",
     "Files" : [ "abc.html","xyz.html", 
                "mnp.html"],
     "Permission" : 555
  }
 ]

i want to read each files in "Files" one by one which lies in "Directory", and change its "Permissions"

Following is the code i have started, Pls Help :

#!/usr/bin/perl

use JSON;
my $filename = 'demo.json';

my $data;
{
    local $/ = undef;
    open my $fh, '<', $filename;
    $data = <$fh>;
    close $fh;
}

my $result = decode_json( $data );

for my $report ( @{$result} ) {

Upvotes: 2

Views: 253

Answers (1)

TLP
TLP

Reputation: 67900

Using your own code, you can easily de-reference the json-structure to simpler structures:

my @files = @{ $result->[0]{Files} };
my $perm = $result->[0]{Permission};

print Dumper \@files, $perm;

Which will print:

$VAR1 = [
          'abc.html',
          'xyz.html',
          'mnp.html'
        ];
$VAR2 = 555;

Then you can loop over the files with a simple for loop:

for my $file (@files) { ...

And chmod files as necessary. Though you may have to prepare the number 555 to be an octal, as described in the documentation.

And if you have several levels of this array that you call "reports", you can loop over them like so:

for my $report (@{ $result }) {
    my @files = @{ $report->{Files} };
    my $perm = $report->{Permission};
    print Dumper \@files, $perm;
}

Upvotes: 3

Related Questions