我正在学习 Perl。当对象包含在数组中时,我能够成功地迭代 JSON 集合。但是,我无法理解如何使用 JSON 数据,其中对象不在数组中并且具有随机标识符(例如,0y7vfr1234
)事先不知道。以下是我尝试读取、更新并保存回文件的结构的一些示例数据。
{
"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。
答案1
像这样 :
#!/usr/bin/perl
use JSON;
use utf8;
use strict; use warnings;
my $data = '{
"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
}
}';
my $json = decode_json $data;
foreach my $key (keys %$json) {
print "$key\n";
}
print "$json->{v2rbz1568}->{username}\n";
输出
v2rbz1568
0y7vfr1234
0zjk1156
[email protected]