我一直在用 Perl 构建模拟器,我面临的问题之一是解析位于计算机中的 JSON 文件。当我尝试从我的服务器获取它们时,它们工作正常...
method getContent(\@arrURLS) {
my %arrInfo;
my $resUserAgent = Mojo::UserAgent->new;
foreach my $strURL (@arrURLS) {
$resUserAgent->get($strURL => sub {
my($resUserAgent, $tx) = @_;
if ($tx->success) {
my $strName = basename($strURL, '.json');
my $arrData = $tx->res->body;
$arrInfo{$strName} = $arrData;
}
Mojo::IOLoop->stop;
});
Mojo::IOLoop->start;
}
return \%arrInfo;
}
假设 @arrURLS
是:
my @arrURLS = ("file:///C:/Users/Test/Desktop/JSONS/first.json", "file:///C:/Users/Test/Desktop/JSONS/second.json");
上面的 url 是不起作用的,但是如果我将其更改为:
my @arrURLS = ("http://127.0.0.1/test/json/first.json", "http://127.0.0.1/test/json/second.json");
有效。
此外,我想使用比 Mojo::UserAgent
更好的东西,因为当我将 Coro
与 LWP::Simple 一起使用时,它看起来有点慢
它要快得多,但不幸的是 Coro
在 Perl 5.22 中损坏了...
最佳答案
User Agent主要是通过http下载文件。通常不希望它们处理文件系统 URI。你需要 open
和 read the file自己,或使用类似 File::Slurp 的模块那就是为你做的。
它可能看起来像这样。
use File::Slurp 'read_file';
method getContent(\@arrURLS) {
my %arrInfo;
my $resUserAgent = Mojo::UserAgent->new;
foreach my $strURL (@arrURLS) {
if (substr($strURL, 0, 4) eq 'file') {
$arrInfo{basename($strURL, '.json')} = read_file($strURL);
} else {
$resUserAgent->get($strURL => sub {
my($resUserAgent, $tx) = @_;
if ($tx->success) {
my $strName = basename($strURL, '.json');
my $arrData = $tx->res->body;
$arrInfo{$strName} = $arrData;
}
Mojo::IOLoop->stop;
});
Mojo::IOLoop->start;
}
}
return \%arrInfo;
}
关于json - 在 Perl 中获取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36803541/