Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

How to get perl json access hash reference

I am trying to get remote host value which is remotehost . I decoded the json and able to get $name and $id values. but getting

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
          }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
 "remote": [
        {
            "host": "remotehost",
            "name": "remotetest"
        }
    ]

This bit is an array of objects (hashes in Perl). You cannot coerce it. You need to access the 1st element.

#   A
#   |           B    
#   |           |    C
#   |           |    |
$obj{'remote'}->[0]->{'host'}

Note there's no auth in this, because that's on the same level as remote (marked as A).

 {
    "auth" : {
        "req": "1234",
        "link": "http://localhost" 
    },
    "host" : "localhost",
    "name" : "mytest",

    // A
    "remote" : [ // B

        { // C
            "host": "remotehost",
            "name": "remotetest"
        }
    ]
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...