Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Decoding JSON in Perl. JSON output as multiple lines

How can I use perl to process JSON, so that instead of one line several lines are output as a structure?

my $json_string = '{"status":"success","answer":{"status":"success","result":{"full_fqdn":"example.com","result":"blablabla","php_version":"8.0","cgi":"disabled"}}}';

I want to get a result like the one on this output:

"status": "success",
"answer": {
    "status": "success",
    "result": {
        "full_fqdn": "example.com",
        "result": "blablabla",
        "php_version": "8.0",
        "cgi": "disabled"
    }
}

I don’t quite understand the proper use of JSON to convert the output this way. Thank you!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

JSON::PP is a core module. The pretty method enables the indenting and spaces around colons. You can control the details with indent, indent_length, space_before, and space_after.

#!/usr/bin/perl
use warnings;
use strict;

use JSON::PP;

my $json_string = '{"status":"success","answer":{"status":"success","result":{"full_fqdn":"example.com","result":"blablabla","php_version":"8.0","cgi":"disabled"}}}';

my $j = 'JSON::PP'->new->pretty;
print $j->encode($j->decode($json_string));

If you need faster processing, install Cpanel::JSON::XS from CPAN.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading