如何在Perl中将字符串转换为json [英] How to convert string to json in perl
问题描述
我对perl还是很陌生,所以请帮助我
I am very new to perl so please help me out in following
我有一个Perl脚本来执行telnet命令.该脚本以字符串形式接收来自服务器的响应.实际上,服务器创建了一个json字符串,然后将其发送到客户端程序,但是客户端程序将其显示为string
I have one perl script to execute telnet command. This script receives response from server as string. Actually server create a json string and then it sends to client program but client program is showing it as string
问题:如何将这个字符串转换为json并从此json字符串读取数据.
Question : How I can convert this string to json and read data from this json string.
我有一个json字符串,其结构类似于以下内容
I have json string with structure similar to following
[{"success":"21","data":[{"name":"tester","lastname":"project"}]}]
以下是我尝试将其转换为json的最后几行
Following are the last lines where I have tried to convert it to json
@lines = $telnet->waitfor('/$/');
my @json;
@json = @{decode_json(@lines)};
它打印输出如下
HASH(0x1af068c)
提前感谢!!!
推荐答案
以下是用于转换JSON的代码段.修改以捕获错误.
Here is a snippet to convert the JSON. Modified to catch errors.
use strict;
use warnings;
use JSON::XS;
use Try::Tiny;
use Data::Dumper::Concise;
my $data = qq<[{"success":"21","data":[{"name":"tester","lastname":"project"}]}]>;
my $decoded;
try {
$decoded = JSON::XS::decode_json($data);
}
catch {
warn "Caught JSON::XS decode error: $_";
};
print Dumper $decoded;
这篇关于如何在Perl中将字符串转换为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!