Perl解析内部数组的JSON

问题描述 投票:1回答:1

[嗨,我是perl和解析json的新手。下面是DB API的json输出。


{
  "limit": 50,
  "page": 1,
  "result": [
    {
      "var1": "var1_1",
      "var2": "var2_1",
      "created_at": "2019-10-06T15:52:37.705950+00:00",
      "id": 2,
      "updated_at": "2019-10-06T15:52:37.705950+00:00",
      "var3": "var3_1"
    },
    {
      "var1": "var1_2",
      "var2": "var2_2",
      "created_at": "2019-10-06T14:17:35.951395+00:00",
      "id": 1,
      "updated_at": "2019-10-06T14:17:35.951395+00:00",
      "var3": "var3_1"
      }
    ],
  "success": true,
  "total_results": 2
}

如何从最新ID(此处为2)获取var1 ??

我在下面这样尝试过。

    use LWP::Simple;
    $contents = get($db_url);
    print "$contents\n";  # print the above output
    my $fromjson = from_json($contents);
    my $data1 = $fromjson->{'limit'};
    print "$data1"; # print properly 50
    my $data2 = $fromjson->{'result'};
    my $data1 = to_json($data2);
    my $data_var1=$data1->{'var1'}; # Tried like this but not getting proper output

请帮助我尝试了不同的方法,但没有通过。

arrays json perl hash
1个回答
2
投票
my $data2 = $fromjson->{'result'};返回数组引用。您可以在Perl Reference Tutorial中了解参考。

如果只需要结果中的第一项,请先获取数组引用。

my $results = $fromjson->{result};

然后是第一个结果,它是一个哈希引用。

my $first_result = $results->[0];

最后得到var1键的值。

my $var1 = $first_result->{var1};

您也可以将其链接在一起,尽管它会使错误处理更加困难。

my $var1 = $from_json->{result}[0]{var1};

© www.soinside.com 2019 - 2024. All rights reserved.