首页 > 解决方案 > 从 Raku HTTP 客户端请求中提取 JSON

问题描述

我无法理解这个 Raku 代码有什么问题。

我想从网站获取 JSON,并从 JSON 中的数组中的每个项目打印出一个字段(在本例中是来自任何 Discourse 论坛的最新主题的标题)。

这是我希望工作的代码,但它失败了:

use HTTP::UserAgent;
use JSON::Tiny;

my $client = HTTP::UserAgent.new;
$client.timeout = 10;

my $url = 'https://meta.discourse.org/latest.json';
my $resp = $client.get($url);

my %data = from-json($resp.content);

# I think the problem starts here.
my @topics = %data<topic_list><topics>;
say @topics.WHAT;  #=> (Array)


for @topics -> $topic {
    say $topic<fancy_title>;
}

错误消息来自以下say $topic<fancy_title>行:

Type Array does not support associative indexing.
  in block <unit> at http-clients/http.raku line 18

我本来希望$topic应该写成%topic,因为它是一个哈希数组,但这不起作用:

for @topics -> %topic {
    say %topic<fancy_title>;
}

错误消息是:

Type check failed in binding to parameter '%topic'; expected Associative but got Array ([{:archetype("regula...)
  in block <unit> at http-clients/http.raku line 17

如果您检查数据,它应该是一个散列,而不是一个数组。我试过@array了,但我知道这是不正确的,所以我%topic改为$topic.

我终于通过添加.list到定义的行来让它工作,@topics但我不明白为什么要修复它,因为@topics是否(Array)添加了它。

这是工作代码:

use HTTP::UserAgent;
use JSON::Tiny;

my $client = HTTP::UserAgent.new;
$client.timeout = 10;

my $url = 'https://meta.discourse.org/latest.json';
my $resp = $client.get($url);

my %data = from-json($resp.content);

# Adding `.list` here makes it work, but the type doesn't change.
# Why is `.list` needed?
my @topics = %data<topic_list><topics>.list;
say @topics.WHAT;  #=> (Array)

# Why is it `$topic` instead of `%topic`?
for @topics -> $topic {
    say $topic<fancy_title>;
}

有谁知道它为什么失败以及执行此任务的正确方法?

标签: raku

解决方案



推荐阅读