如何使用Perl将其他数据添加到JSON格式的配置文件中?

时间:2015-07-23 09:41:36

标签: json perl

我正在编写一个脚本,它从MySQL数据库中检索一些信息,以便在dhcp conf文件中生成静态预留。 dhcp conf文件采用JSON格式。

所以我有这样的信息:

"subnet4": [
    {   
        "subnet": "192.168.2.0/24",
        "pools": [ 
           { "pool": "192.168.2.10 - 192.168.2.20" }
        ]
    }
 ]

我想要这样的事情:

"subnet4": [
    {
        "pools": [ { "pool":  "192.0.2.1 - 192.0.2.200" } ],
        "subnet": "192.0.2.0/24",
        "interface": "eth0",
        "reservations": [
            {
                "hw-address": "1a:1b:1c:1d:1e:1f",
                "ip-address": "192.0.2.202"
            },
            {
                "hw-address": "0a:0b:0c:0d:0e:0f",
                "ip-address": "192.0.2.100",
            }
        ]
    }
]

为达到这个目的,现在我可以生成“预订”,我得到了这个:

[{"ip-address":"192.0.2.202","hw-address":"1a:1b:1c:1d:1e:1f"},{"ip-address":"192.0.2.100","hw-address":"0a:0b:0c:0d:0e:0f"}]

我正在通过perl脚本执行此操作,现在我想通过一个循环将其添加到dhcp.conf文件中,逐行读取我的文件以添加字段“预留”以及其中的每个信息但是我不要成功地匹配一个pettern添加这个我想要的。因为我有不同的子网设置所以我不能在我的子网字段中使用信息来匹配patern并在它之后添加保留...

有人有想法吗?

谢谢!

2 个答案:

答案 0 :(得分:5)

此问题被标记为正则表达式。不要使用正则表达式执行此任务,这是令人讨厌的。请改用JSON模块。像这样:

#!/usr/bin/env perl
use strict;
use warnings;
use JSON;
use Data::Dumper;

my $raw_text = '{"subnet4": [
    {   
        "subnet": "192.168.2.0/24",
        "pools": [ 
           { "pool": "192.168.2.10 - 192.168.2.20" }
        ]
    }
 ]}';

my $json = decode_json($raw_text);

$json->{'subnet4'}->[0]->{"interface"} = "eth0";
my $reservations = $json->{"subnet4"}->[0]->{'reservations'} = [];

push(
    @$reservations,
    {   "hw_address" => "1a:1b:1c:1d:1e:1f",
        "ip-address" => "192.0.2.202"
    }
);
push(
    @$reservations,
    {   "hw_address" => "0a:0b:0c:0d:0e:0f",
        "ip-address" => "192.0.2.100"
    }
);

print Dumper $json;

print "JSON Result:\n";

print to_json($json, {'pretty' => 1 } );

这会产生:

{
   "subnet4" : [
      {
         "reservations" : [
            {
               "ip-address" : "192.0.2.202",
               "hw_address" : "1a:1b:1c:1d:1e:1f"
            },
            {
               "ip-address" : "192.0.2.100",
               "hw_address" : "0a:0b:0c:0d:0e:0f"
            }
         ],
         "subnet" : "192.168.2.0/24",
         "pools" : [
            {
               "pool" : "192.168.2.10 - 192.168.2.20"
            }
         ],
         "interface" : "eth0"
      }
   ]
}

答案 1 :(得分:0)

好的,我找到了解决方案,

open(my $json_fh, "<:encoding(UTF-8)", $kea_conf_file_path)
  or die("Can't open \$kea_conf_file_path\": $!\n");
my $json_text;
while (my $line = <$json_fh>) {
        unless($line =~ m/^#/){
                $json_text .= $line; 
        }
}
my $json = decode_json($json_text);
my $reservations = $json->{"Dhcp4"}->{"subnet4"}->[0]->{'reservations'} = [];
push @$reservations, @reservation_from_db;
print Dumper $json;

非常感谢@Sobrique,它更加可读和干净。