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

Categories

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
          }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

 "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"
        }
    ]
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...