Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to json in perl

Tags:

json

perl

I am very new to perl so please help me out in following

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

Question : How I can convert this string to json and read data from this json string.

I have json string with structure similar to following

[{"success":"21","data":[{"name":"tester","lastname":"project"}]}]

Following are the last lines where I have tried to convert it to json

@lines = $telnet->waitfor('/$/');
my @json;
@json = @{decode_json(@lines)};

It prints output as below

HASH(0x1af068c)

Thanks in advance !!!

like image 320
Yogesh Avatar asked Dec 28 '22 08:12

Yogesh


2 Answers

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;
like image 84
Bill Ruppert Avatar answered Jan 07 '23 16:01

Bill Ruppert


I think there is a simpler one:

use JSON ();

$content = "{WHATEVER JSON CONTENT}";

$content = JSON->new->utf8->decode($content);
like image 28
Nahuelsgk Avatar answered Jan 07 '23 18:01

Nahuelsgk