如何获取 perl json 访问哈希引用
How to get perl json access hash reference
我正在尝试获取 remotehost 的远程主机值。我解码了 json 并能够获得 $name 和 $id 值。但得到
Bad index while coercing array into hash while accessing 'remote -> host value which is remotehost.
my $json input is
[
{
"auth":{
"req": "1234",
"link": "http://localhost"
},
"host": "localhost",
"name": "mytest",
"remote": [
{
"host": "remotehost",
"name": "remotetest"
}
]
}
]
#My code
use JSON qw( decode_json );
use Data::Dumper;
my $list = decode_json($json) ;
my @array = @{$list};
foreach(@array)
{
my %obj = %{$_};
my $id = $obj{'auth'}{'link'};
my $name = $obj{'name'};
my $remotehost = $obj{'auth'}->{'remote'}{'host'}; #getting error
}
"remote": [
{
"host": "remotehost",
"name": "remotetest"
}
]
这个位是一个对象数组(Perl 中的散列)。你不能强迫它。您需要访问第一个元素。
# A
# | B
# | | C
# | | |
$obj{'remote'}->[0]->{'host'}
请注意,这里没有 auth
,因为它与 remote
(标记为 A)处于同一级别。
{
"auth" : {
"req": "1234",
"link": "http://localhost"
},
"host" : "localhost",
"name" : "mytest",
// A
"remote" : [ // B
{ // C
"host": "remotehost",
"name": "remotetest"
}
]
}
我正在尝试获取 remotehost 的远程主机值。我解码了 json 并能够获得 $name 和 $id 值。但得到
Bad index while coercing array into hash while accessing 'remote -> host value which is remotehost.
my $json input is
[
{
"auth":{
"req": "1234",
"link": "http://localhost"
},
"host": "localhost",
"name": "mytest",
"remote": [
{
"host": "remotehost",
"name": "remotetest"
}
]
}
]
#My code
use JSON qw( decode_json );
use Data::Dumper;
my $list = decode_json($json) ;
my @array = @{$list};
foreach(@array)
{
my %obj = %{$_};
my $id = $obj{'auth'}{'link'};
my $name = $obj{'name'};
my $remotehost = $obj{'auth'}->{'remote'}{'host'}; #getting error
}
"remote": [
{
"host": "remotehost",
"name": "remotetest"
}
]
这个位是一个对象数组(Perl 中的散列)。你不能强迫它。您需要访问第一个元素。
# A
# | B
# | | C
# | | |
$obj{'remote'}->[0]->{'host'}
请注意,这里没有 auth
,因为它与 remote
(标记为 A)处于同一级别。
{
"auth" : {
"req": "1234",
"link": "http://localhost"
},
"host" : "localhost",
"name" : "mytest",
// A
"remote" : [ // B
{ // C
"host": "remotehost",
"name": "remotetest"
}
]
}