Search code examples
perlperl-module

json parsing using perl


I have a huge json file ~1000+ lines. I wanted to implement two things.

1) In the json file,if "Id" : "232799" then assign "s" as "1861" I did this using decode_json. It works as expected.

2)Increment the version number by 1 and save the file in a particular directory. I want this to happen in a loop .

I believe decode_json should be used to parse json object/json array. However, version is the first line in the file.I'm not really sure if decode could be used.Any suggestions?

{
    "version": "16300173",
    "con": {
        "s1": {
            "key": false,
            "global": {
                "cu": [
                    {
                        "Id": "232799",
                        "s": 1861,
                        "Sps": "xx",
                        "cId": "xyzzde",
                        "pat": "-123456789",
                        "Config": true,
                        "auth": [
                            {
                                "Type": "5",
                                "dir": "in"
                            },
                            {
                                "Type": "6",
                                "dir": "out"
                            }
                        ],

script :

  #!/usr/bin/perl

    use strict;
    use warnings;
    use JSON;

    my $json;
    {
       open my $fh, "<", "/a/etc/cm/nw/st/cfg.json"
          or die("Can't open file \"/a/etc/cm/nw/st/cfg.json\": $!\n");
       local $/;
       $json = <$fh>;
    }

    my $data = decode_json($json);

    for my $customers (@{ $data->{global}{cu} }) {
   $customers->{s} = 1861
      if $customers->{id} ==237299;

}

    $json = JSON->new->utf8->pretty->encode($data);

    {
       open my $fh, ">" ,"/a/etc/cm/nw/st/cfg.json"
          or die("Can't open file \"/a/etc/cm/nw/st/cfg.json\": $!\n");
       local $/;

       print $fh $json;


    }

Solution

  • As well as the missing {con}{s1} keys, you have id instead of Id

    This code appears to work

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    use v5.14.1;  # for autodie
    use autodie;
    
    use JSON;
    
    use constant JSON_FILE => '/a/etc/cm/nw/st/cfg.json';
    
    my $data = do {
        open my $fh, '<', JSON_FILE;
        local $/;
        decode_json(<$fh>);
    };
    
    my $cu = $data->{con}{s1}{global}{cu};
    
    for my $cust ( @$cu ) {
        $cust->{s} = 1861 if $cust->{Id} == 232799;
    }
    
    ++$data->{version};
    
    {
        open my $fh, '>', JSON_FILE;
        print $fh JSON->new->utf8->pretty->encode($data);
    }