使用perl解析json文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15653419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:49:59  来源:igfitidea点击:

parsing json file using perl

jsonperl

提问by UKR

I am trying to parse a json file in perl. I want to extract the key "name" and corresponding value of it. my file looks like this

我正在尝试用 perl 解析一个 json 文件。我想提取键“名称”及其对应的值。我的文件看起来像这样

{
 "data":[
    {
        "name":"ABC",
        "id":"123",
    },
    {
        "name":"PQR",
        "id":"456",
    },
    {
        "name":"XYZ",
        "id":"789",
    }
]
}

I am trying with below code:

我正在尝试使用以下代码:

#/usr/lib/perl
use lib qw( ..);
use LWP::Simple;
use JSON;
my $filename = '/file.txt';
my $data;
if (open (my $json_str, $filename))
{
  local $/ = undef;
  my $json = JSON->new;
  $data = $json->decode(<$json_str>);
  close($json_stream);
}
print $data->{name};

But I not getting any output.

但我没有得到任何输出。

Can anyone tel me what is wrong ?

谁能告诉我出了什么问题?

回答by average

Your json file is invalid.

您的 json 文件无效。

Lines 5,10,15 should not end with a comma since that is the last key/value pair of those hashes.

第 5、10、15 行不应以逗号结尾,因为这是这些散列的最后一个键/值对。

After you fix that, here is a version of your code that gives you the expected result:

修复此问题后,这里是您的代码版本,可为您提供预期结果:

#/usr/lib/perl
use strict;
use warnings;

use lib qw(..);

use JSON qw( );

my $filename = 'file.txt';

my $json_text = do {
   open(my $json_fh, "<:encoding(UTF-8)", $filename)
      or die("Can't open $filename\": $!\n");
   local $/;
   <$json_fh>
};

my $json = JSON->new;
my $data = $json->decode($json_text);

for ( @{$data->{data}} ) {
   print $_->{name}."\n";
}

Some of the problems:

一些问题:

  • You were using $json_streamand $json_str. You meant to use $json_streamin all places to denote the filehandle
  • The $data->{name}should be applied to all members of the array in the .json file, not to the json itself. So you need to iterate through them first
  • 您正在使用$json_stream$json_str。您打算$json_stream在所有地方使用来表示文件句柄
  • $data->{name}应在上传.json文件被施加到所述阵列的所有成员,而不是到JSON本身。所以你需要先遍历它们

When debugging this, make sure your json is valid. Either through jsonlint.comor the json_xsutility that comes with JSON::XSfrom cpan.

调试时,请确保您的 json 有效。通过jsonlint.com或来自 cpan 的JSON::XS附带的json_xs实用程序。

JSON can describe complicated data structures so when you parse it into Perl you get a complex data structure too. Try to first have a look at the data structure using Data::Dumperor Data::Printeror Data::TreeDumper

JSON 可以描述复杂的数据结构,因此当您将其解析为 Perl 时,您也会得到一个复杂的数据结构。尝试首先使用Data::DumperData::PrinterData::TreeDumper查看数据结构

回答by TLP

Besides having an extra comma in the JSON string, you do not reference the right values. Always use

除了在 JSON 字符串中有一个额外的逗号之外,您没有引用正确的值。一直使用

use strict; 
use warnings;

-- they will tell you what's wrong. In this case, you are printing an undefined value $data->{name}, a variable that has not been assigned a value. If you print your decoded structure in Data::Dumperit looks like this:

——他们会告诉你出了什么问题。在这种情况下,您正在打印一个 undefined value $data->{name},一个尚未赋值的变量。如果您在Data::Dumper其中打印解码结构,则如下所示:

$VAR1 = {
          'data' => [
                      {
                        'name' => 'ABC',
                        'id' => '123'
                      },
                      {
                        'name' => 'PQR',
                        'id' => '456'
                      },
                      {
                        'name' => 'XYZ',
                        'id' => '789'
                      }
                    ]
        };

And as you can see, $datais actually a hash reference, where the first and only key is called 'data', whose value is an array with three elements, each containing a hash reference. So, in order to print those elements you would do something like:

正如你所看到的,$data实际上是一个散列引用,其中第一个也是唯一一个键被称为'data',其值是一个包含三个元素的数组,每个元素包含一个散列引用。因此,为了打印这些元素,您可以执行以下操作:

print $data->{data}[0]{name};   # prints ABC

my $aref = $data->{data};
for my $element (@$aref) {
    print $element->{name};     # prints ABC, PQR, XYZ
}