Op 29-06-16 om 06:35 schreef Danny Wong:
Hi Perl GURUs,
I have a json file that needs parsing.

Here is a typical string I’m searching for. I want to delete everything but the last 2 character “],”.

    ],

    [

      "ansible",

      "2.1.0.0-1ppa~trusty",

      false

    ],


Here is what I tried:


I slurp the whole file into a variable.

my $SAVE = $/;

my $WHOLE_JSON_FILE = `cat ${JSON_FILE}`;

$/ = $SAVE;


while($WHOLE_JSON_FILE !~ /.*?(\s+\]\,\s+\[\s+\"ansible\".*?)\]\,?/gs)

{

print "\$1 is $1";

}


The print statement is printing out the “matching string” but how do I remove that section of string from the slurp $WHOLE_JSON_FILE variable which contains the entire file content?



Hi Danny,

JSON is a strictly defined data format. Modifying such a file with regular expressions will sooner or later break the structure of your config file in a nasty way. The same goes for XML, HTML en the like. Therefore the real guru's have created modules to help us keep these files sane.

Before today I never tried my hand on JSON, but I managed to get something working that might give you
an idea of how to work with the JSON module.
Given a json file that looks like this:
{
   "JSON" : [
      [
         "a",
         "b",
         "c"
      ],
      [
         "d",
         "e",
         "f"
      ],
      [
         "g",
         "h",
         "i"
      ]
   ]
}

This script removes the second array (it tests for "d", you would change that to "ansible"):
#!/usr/bin/env perl

use strict;
use warnings;

use JSON;

my $json = JSON->new->pretty;

my $json_data_in = slurp_file('JSON_FILE');

my $data = $json->decode($json_data_in);

my $new_data = {JSON => []};

foreach my $array ($data->{JSON}) {
    foreach my $subarray (@$array) {
        next if $subarray->[0] eq 'd';
        push @{$new_data->{JSON}},[@{$subarray}];
    }
}

my $json_data_out = $json->encode($new_data);

write_file('JSON_FILE_NEW', $json_data_out);

sub slurp_file {
    my $file = shift;
    local $/;
    open my $fh, '<', $file or die "Can't open $_: $!\n";
    <$fh>;
}

sub write_file {
    my $file = shift;
    open my $fh, '>', $file or die "Can't open $_: $!\n";
    print $fh @_ ;
}

The file JSON_FILE_NEW now looks like:
{
   "JSON" : [
      [
         "a",
         "b",
         "c"
      ],
      [
         "g",
         "h",
         "i"
      ]
   ]
}

It's a bit quick and dirty hacked together, but I hope it will point you in the right direction. B.T.W. I tested this script using perl 5.20. I expect it to work with older Perl versions as well.
Comments by others are welcome, of course.

Greetings,
Eric de Hont

Reply via email to