我正在学习 Perl。当对象包含在数组中时,我已经能够成功地遍历 JSON 集合。但是,我无法理解如何处理对象不在数组中并且具有事先不知道的0y7vfr1234
随机标识符(例如)的 JSON 数据。这是我尝试读取、更新并保存回文件的结构的一些示例数据。
{
"0y7vfr1234": {
"username": "[email protected]",
"password": "some-random-password123",
"uri": "ww1.example.com",
"index": 14
},
"v2rbz1568": {
"username": "[email protected]",
"password": "some-random-password125",
"uri": "ww3.example.com",
"index": 29
},
"0zjk1156": {
"username": "[email protected]",
"password": "some-random-password124",
"uri": "ww2.example.com",
"index": 38
}
}
如果这些对象都在一个数组中,我会这样做:
#!/usr/bin/perl
use lib qw(..);
use JSON;
binmode STDOUT, ":utf8";
use utf8;
use strict;
use warnings;
my $filename1 = 'input.json';
my $filename2 = 'serverlist.txt';
my $json_text = do {
open(my $json_fh, "<:encoding(UTF-8)", $filename1)
or die("Can't open \$filename1\": $!\n");
local $/;
<$json_fh>
};
open my $server_list, '<', $filename2 or die "Can't open $filename2: $!";
my @server_list = <$server_list>;
close $server_list or die "Can't close $server_list: $!";
my $json = JSON->new;
my $data = $json->decode($json_text);
my $aref = $data->{the_array_name};
for my $setting (@$aref) {
if (length $setting->{uri}) { #no warnings
$setting->{uri} =~ m/^ww(\d+)\.example.com/;
my $server_number = $1;
print "checking $server_number ... \n";
if (grep{/$setting->{uri}/} @server_list) {
print "server number is: $server_number\n";
} else {
# 1. iterate through the sorted list
foreach (@server_list)
{
$_ =~ m/^ww(\d+)\.example.com/;
my $new_num = $1;
# 2. find the next match in order
if ( $new_num > $server_number ) {
print "Found it: new server number $new_num is greater than $server_number\n";
# TODO 3. check that it does not exist in $data->{the_array_name};
# 4. replace $setting->{uri} with new value
my $new_server = $_;
$new_server =~ s/\s+$//;
$setting->{uri} = $new_server;
last;
}
}
}
}
}
# 5. save JSON as a file to disk.
my $filename3 = 'output.json';
open my $proxy_settings, '>', $filename3 or die "Can't open $filename3: $!";
print $proxy_settings encode_json($data);
close $proxy_settings or die "Can't close $proxy_settings: $!";
这是我写的第一个 Perl。我还没有 100% 理解它的每一行。(例如:)binmode STDOUT, ":utf8";
。我确信它远非最佳,我会继续努力。我的问题是,如何修改它以使用上面显示的 JSON 结构?
我在 Linux 上使用 perl 5,版本 30。
像这样 :
输出