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

如何将JSON格式的HTTP响应转换为Perl哈希?

解决Perl中JSON字符串转哈希的问题

嘿,这事儿其实超简单的!你已经引入了JSON模块,直接用它的decode_json函数就能把JSON字符串转换成Perl能直接操作的哈希引用啦。

完整代码示例

use JSON;
use LWP::Simple;

my $url = "http://127.0.0.1:3000";
my $response = get $url;

# 将JSON字符串解析为哈希引用
my $response_hash = decode_json($response);

# 直接访问answer字段(注意用->访问引用)
print $response_hash->{answer};  # 输出结果:16.0

# 如果你需要普通哈希而非引用,也可以解引用
my %response_hash_plain = %$response_hash;
print $response_hash_plain{answer};  # 同样能输出16.0

额外的健壮性建议

实际开发中最好加上错误处理,避免网络请求失败或者JSON格式异常导致脚本崩溃:

use JSON;
use LWP::Simple;

my $url = "http://127.0.0.1:3000";
my $response = get $url;

# 检查网络请求是否成功
unless ($response) {
    die "无法从$url获取数据,请检查服务是否运行";
}

my $response_hash;
# 捕获JSON解析可能出现的错误
eval {
    $response_hash = decode_json($response);
};
if ($@) {
    die "JSON解析失败:$@";
}

print $response_hash->{answer};

简单解释下:decode_json会把JSON对象转换成Perl的哈希引用,JSON数组则会转换成数组引用——刚好匹配你的返回结果格式。之后你就可以像操作普通哈希一样(注意引用的访问语法是->),轻松获取answer或者string字段的值啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:48:55