json - 在 Perl 中获取 JSON

标签 json perl http get mojolicious

我一直在用 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 更好的东西,因为当我将 CoroLWP::Simple 一起使用时,它看起来有点慢 它要快得多,但不幸的是 Coro 在 Perl 5.22 中损坏了...

最佳答案

User Agent主要是通过http下载文件。通常不希望它们处理文件系统 URI。你需要 openread 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/

相关文章:

javascript - 在带有特殊字符的 HTML 中显示原始 JSON

java - 将 mysql 查询结果推送到客户端 GWT

javascript - 在js中创建嵌套Json

Perl CGI 持久性 cookie

php - 在 PMWIKI 中通过 HTTPS 或 HTTP 加载 CSS 和 JS

objective-c - 如何在 Objective-C 中遍历一个简单的 JSON 对象?

perl - 解析逻辑表达式并将其转换为 Perl 中的树

perl - 如何从今天开始计算一周前的日期

java - 使用 HTTP 协议(protocol)通过 TCP 套接字获取图像

java - 我可以在谷歌应用引擎中使用 org.apache.http.client.HttpClient 吗?