0

I'm looping through the decoded JSON returned from Pingdom's "Get Detailed Check Information"-API. I'm trying to print the URL in the JSON data, but I'm having a hard time doing so.

Here is the JSON response I got:

{
  "check" : {
    "id" : 85975,
    "name" : "My check 7",
    "resolution" : 1,
    "sendtoemail" : false,
    "sendtosms" : false,
    "sendtotwitter" : false,
    "sendtoiphone" : false,
    "sendnotificationwhendown" : 0,
    "notifyagainevery" : 0,
    "notifywhenbackup" : false,
    "created" : 1240394682,
    "type" : {
      "http" : {
        "url" : "/",
        "port" : 80,
        "requestheaders" : {
          "User-Agent" : "Pingdom.com_bot_version_1.4_(http://www.pingdom.com/)"
        }
      }
    },
    "hostname" : "s7.mydomain.com",
    "status" : "up",
    "lasterrortime" : 1293143467,
    "lasttesttime" : 1294064823
  }
}

And here's my Perl code that should print the URL:

my $decoded_info = decode_json($json) or die "Failed to decode!\n";
foreach my $check( $decoded_info->{check}) {
  print "$decoded_info->{$check}->{type}->{http}->{url}\n";
}

I've read the Perl reference and a tutorial but it still doesn't work.

Sainan
  • 1,274
  • 2
  • 19
  • 32
Stephens
  • 3
  • 2

2 Answers2

1

You want

$decoded_info->{check}->{type}->{http}->{url}    # ok

and $check has the value of

$decoded_info->{check};

so you should be using

$check->{type}->{http}->{url}                    # ok

instead of

$decoded_info->{$check}->{type}->{http}->{url}   # BAD

By the way,

my $check = $decoded_info->{check};
...

is simpler than

foreach my $check( $decoded_info->{check}) {
    ...
}
ikegami
  • 367,544
  • 15
  • 269
  • 518
0

There is only one item inside of the check.

{
  "check" : {                     // here
    "id" : 85975,
    "name" : "My check 7",
    "resolution" : 1,
    "sendtoemail" : false,
    "sendtosms" : false,
    "sendtotwitter" : false,
    "sendtoiphone" : false,
    "sendnotificationwhendown" : 0,
    "notifyagainevery" : 0,
    "notifywhenbackup" : false,
    "created" : 1240394682,
    "type" : {
      "http" : {
        "url" : "/",
        "port" : 80,
        "requestheaders" : {
          "User-Agent" : "Pingdom.com_bot_version_1.4_(http://www.pingdom.com/)"
        }
      }
    },
    "hostname" : "s7.mydomain.com",
    "status" : "up",
    "lasterrortime" : 1293143467,
    "lasttesttime" : 1294064823
  }
}

There is no reason to iterate over anything. You can get rid of the foreach loop and simply use the string check as your hash key.

#                      vvvvv
print "$decoded_info->{check}->{type}->{http}->{url}\n";
simbabque
  • 53,749
  • 8
  • 73
  • 136