@edit #Clarity
Objective: API Testing
Functionality: Reads the API.json and parses it. User inputs a key and gets the value.
Problem: The value for the key active equals "true" or "false", script prints "1" or " ".
Code:
use strict;
use warnings;
use JSON;
use JSON::Parse 'parse_json';
print "Loading API.\n";
my $json = `curl -k --silent -u admin:pass https://url...`;
print "API is loaded.\n";
my $decoded_json = parse_json ($json);
my $input = <STDIN>;
chomp $input;
my ($item, $mac);
foreach $item (@$decoded_json) {
my $mac = $item->{address};
if ($input eq "active") {
@$value = $item->{active};
if ($value eq 1){
print ("Device with the MAC-Adress: $mac is active!\n");
}elsif($value eq 0){
print ("Device with the MAC-Adress: $mac is disabled!\n");
}else{
print ("Device with the MAC-Adress: $mac, $input is: ", $item->{$input}, "\n");
}
};
Output when user asks for id:
Device with MAC-Adress: xx:xx:xx:xx:xx:xx, id is: 6
Output when user asks for device status:
Device with the MAC-Adress: xx:xx:xx:xx:xx:xx, active is: 1
or
Device with the MAC-Adress: xx:xx:xx:xx:xx:xx, active is:
Target: True value prints active and false value prints false.
The script obviously skips the first two ifs, and jumps to the third option and I can´t figure out why... There are no errors shown terminal.
foreach $item (@$decoded_json) {
my $mac = $item->{address};
if ($input eq "active") {
$value = $item->{active};
if ($value eq 1){
print ("Device with the MAC-Adress: $mac is active!\n");
}elsif($value eq ""){
print ("Device with the MAC-Adress: $mac is disabled!\n");
}}else{
print ("Device with the MAC-Adress: $mac, the value of $input is: ", $item->{$input}, "\n");
}
};
I say you need to figure out where in your data structure you need to add the parameter. Here is a example using this sample json API: https://web.archive.org/web/20230607213915/https://www.appsloveworld.com/free-online-sample-rest-api-url-for-testing
Where I use Data::Dumper to look at the data structure then loop thru the structure adding active = true and then dump the structure again:
#!/usr/bin/env perl
use strict;
use warnings;
use JSON;
use JSON::Parse 'parse_json';
use Data::Dumper;
print "Loading API.\n";
# here is a test API we can access for testing
my $json = `curl -k --silent http://restapi.adequateshop.com/api/Tourist?page=1`;
print "API is loaded.\n";
my $decoded_json = parse_json ($json);
print "first use Data Dumper to examine data structure:\n";
print Dumper $decoded_json;
print "\n\nNext create whatever loops you need to access the data, it appears with JSON::Parse the data is in the hash 'data'\n";
foreach my $item (@ {$decoded_json->{data}} ) {
$item->{active} = 'true' if ($item);
foreach my $key ( keys %{$item} ) {
print "$key => $item->{$key} \n";
}
}
print "\n\nlast use Data Dumper to examine data structure again:\n";
print Dumper $decoded_json;