How to convert string to json in perl

I am very new to perl, so please help me with the following

I have one perl script to execute the telnet command. This script receives the response from the server as a string. Actually the server creates a json string and then goes to the client program, but the client program shows it as a string

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

I have a json string with a structure similar to the following

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

Below are the last lines where I tried to convert it to json

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

It prints the output below

 HASH(0x1af068c) 

Thanks in advance!

+4
source share
2 answers

Here is a snippet for JSON conversion. 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; 
+4
source

I think there is a simpler option:

 use JSON (); $content = "{WHATEVER JSON CONTENT}"; $content = JSON->new->utf8->decode($content); 
+1
source

Source: https://habr.com/ru/post/1388285/


All Articles