使用 Perl 遍历 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11641954/
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:28:21  来源:igfitidea点击:

loop over JSON using Perl

jsonperl

提问by Mike

I'm a newbie to Perl and want to loop over this JSON data and just print it out to the screen.

我是 Perl 的新手,想遍历这个 JSON 数据并将其打印到屏幕上。

How can I do that?

我怎样才能做到这一点?

$arr = '[{"Year":"2012","Quarter":"Q3","DataType":"Other 3","Environment":"STEVE","Amount":125},{"Year":"2012","Quarter":"Q4","DataType":"Other 2","Environment":"MIKE","Amount":500}]';

回答by friedo

Use JSONor JSON::XSto decode the JSON into a Perl structure.

使用JSONJSON::XS将 JSON 解码为 Perl 结构。

Simple example:

简单的例子:

use strict;
use warnings;

use JSON::XS;

my $json = '[{"Year":"2012","Quarter":"Q3","DataType":"Other 3","Environment":"STEVE","Amount":125},{"Year":"2012","Quarter":"Q4","DataType":"Other 2","Environment":"MIKE","Amount":500}]';

my $arrayref = decode_json $json;

foreach my $item( @$arrayref ) { 
    # fields are in $item->{Year}, $item->{Quarter}, etc.
}

回答by ikegami

You have an array of hashes.

你有一个哈希数组。

use JSON::XS qw( decode_json );

my $records = decode_json($json_text);
for my $record (@$records) {
   for my $key (keys(%$record)) {
      my $val = $record->{$key};
      say "$key: $val";
    }
}

JSON::XS

JSON::XS

回答by Despertar

Here is a package on CPAN that should do the trick, JSON.pm

这是 CPAN 上的一个包,它应该可以解决问题,JSON.pm

Once you parse it, you can treat it like any other Perl reference.

一旦你解析它,你就可以像对待任何其他 Perl 参考一样对待它。

Example

例子

$perl_scalar = $json->decode($json_text)


Documentation

文档

The opposite of encode: expects a JSON text and tries to parse it, returning the resulting simple scalar or reference. Croaks on error.

JSON numbers and strings become simple Perl scalars. JSON arrays become Perl arrayrefsand JSON objects become Perl hashrefs. true becomes 1 (JSON::true), false becomes 0 (JSON::false) and null becomes undef.`

编码的反面:期望一个 JSON 文本并尝试解析它,返回结果的简单标量或引用。错误的咝咝声。

JSON 数字和字符串成为简单的 Perl 标量。JSON 数组变成 Perl 数组引用,JSON 对象变成 Perl 哈希引用。true 变为 1 (JSON::true),false 变为 0 (JSON::false),null 变为 undef。`

Similar stack overflow question: Parsing an array encoded in JSON

类似的堆栈溢出问题: 解析以 JSON 编码的数组