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

Max*_*rim 0 perl json

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

所以我有这样的信息:

"subnet4": [
    {   
        "subnet": "192.168.2.0/24",
        "pools": [ 
           { "pool": "192.168.2.10 - 192.168.2.20" }
        ]
    }
 ]
Run Code Online (Sandbox Code Playgroud)

我想要这样的东西:

"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",
            }
        ]
    }
]
Run Code Online (Sandbox Code Playgroud)

为了达到这个目标,我现在可以生成"预订",我得到了这个:

[{"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"}]
Run Code Online (Sandbox Code Playgroud)

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

有人有想法吗?

谢谢 !

Sob*_*que 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 } );
Run Code Online (Sandbox Code Playgroud)

这会产生:

{
   "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"
      }
   ]
}
Run Code Online (Sandbox Code Playgroud)

  • 该文件是什么样的?有可能它是所有`JSON`混合`JSON`和纯文本也很肮脏. (3认同)