You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Perl API测试脚本active字段输出异常排查与修复

Perl API JSON解析脚本问题修复

问题说明

这是一款用于API测试的Perl脚本,核心功能是读取并解析API返回的JSON数据,用户输入键名即可获取对应值。当前存在以下问题:

  • 输入键为active时,API返回的实际值是true/false,但脚本输出1或空值
  • 会直接跳过前两个条件判断进入else分支,终端无报错信息
  • 需求目标:true时输出“active”,false时输出“disabled”

原问题代码

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");
    }
};

问题根源分析

  1. 变量类型错误:错误地将active的布尔值赋值给数组引用@$value,而非标量变量,导致后续等值判断逻辑失效
  2. 判断条件不匹配:使用字符串比较符eq判断时,JSON解析后false会被转为空字符串,而非原代码中判断的0
  3. 代码结构混乱:缩进和括号匹配错误,导致条件分支逻辑被破坏,else分支被错误触发

修复后可行代码

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");
    }   
};

修复要点

  • 修正变量类型:将数组引用@$value改为标量$value,正确接收JSON解析后的布尔值(true转为1,false转为空字符串)
  • 调整判断条件:将$value eq 0改为$value eq "",匹配JSON解析后false的实际表现
  • 规范代码结构:修正缩进与括号嵌套,确保条件分支逻辑清晰,避免else分支被错误触发

内容的提问来源于stack exchange,提问作者Jakoby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 14:36:16