gpt4 book ai didi

json - Perl - 从 JSON 到对象/哈希

转载 作者:行者123 更新时间:2023-12-05 08:42:31 24 4
gpt4 key购买 nike

我必须在下面编写代码:

#!/usr/intel/bin/perl

use strict;
use warnings;

use JSON::XS;

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

my $arrayref = decode_json $json;

for my $array(@$arrayref){
for my $key (keys(%$array)){
my $val = $array->{$key};
print "$key: $val\n";
}

}

当我编译它时,它向我打印错误“在 generator.pl 第 12 行不是 ARRAY 引用。”。

我想把JSON解析成对象,根据对象的属性获取数据。我该怎么做?

我希望在我解析它之后,我可以用来比较字符串、打印、循环等等。

最佳答案

不是数组引用,是散列引用:

#!/usr/intel/bin/perl

use strict;
use warnings;

use JSON::XS;
use Data::Dumper;

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

my $arrayref = decode_json $json;

print Data::Dumper->Dump([$arrayref], [qw(arrayref)]);

并输出:

$arrayref = {
'Object2' => {
'Quarter' => 'Q4',
'Year' => '2012',
'Amount' => 500,
'DataType' => 'Other 2',
'Environment' => 'MIKE'
},
'Object1' => {
'Amount' => 125,
'DataType' => 'Other 3',
'Year' => '2012',
'Environment' => 'STEVE',
'Quarter' => 'Q3'
}
};

关于json - Perl - 从 JSON 到对象/哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40839664/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com