【问题标题】:Looping through JSON data and printing out a field using Perl (Not a HASH ref)循环遍历 JSON 数据并使用 Perl 打印出一个字段(不是 HASH 参考)
【发布时间】:2015-12-26 03:02:48
【问题描述】:

我需要遍历几个 json 并打印出每个的索引 1...

我从一个包含我的 JSON 数据的生成字符串开始。然后我解码字符串并转储它以准确显示我正在使用的内容:

my $decoded = decode_json $string
print Dumper $string

这会产生以下输出:

$VAR1 = [
      {
        'hdr' => [
                   1,
                   'acknowledged',
                   '',
                   '/home/clanier/dev/test/sds-test/data/JPLIDR2015169.64575',
                   '2015/271-19:10:39.0101355',
                   '2015/271-19:10:39.2599252',
                   ''
                 ]
      },
      {
        'hdr' => [
                   2,
                   'acknowledged',
                   '',
                   '/home/clanier/dev/test/sds-test/data/JPLIDR2015169.64575',
                   '2015/271-19:10:39.3928414',
                   '2015/271-19:10:39.6397269',
                   ''
                 ]
      },
      {
        'hdr' => [
                   3,
                   'acknowledged',
                   '',
                   '/home/clanier/dev/test/sds-test/data/JPLIDR2015169.64575',
                   '2015/271-19:10:39.7726375',
                   '2015/271-19:10:40.0162758',
                   ''
                 ]
      }
    ];

现在我尝试循环遍历并打印每个单词的确认:

foreach my $hdr ( $decoded->{hdr} ) {
  print $hdr->[1];
}

我向this solution 寻求帮助,但由于“不是 HASH 参考”错误,我什至无法达到原始海报的水平。我以前可以打印一个特定的,但我需要循环并打印所有这些。这是代码:print $$decoded[0]->{'hdr'}->[1];

【问题讨论】:

    标签: json perl hash foreach


    【解决方案1】:

    $decoded 是数组引用,而不是哈希引用。您不能将其取消引用为哈希:->{

    不过,您可以将其取消引用为数组:

    for my $hdr (@$decoded) {
        print $hdr->{hdr}[1];
    }
    

    perlreftut 有关 Perl 中的引用的更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-14
      • 2021-03-20
      • 1970-01-01
      相关资源
      最近更新 更多