0

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!

1
  • I often just let the Perl module do whatever it wants and pretty print it later with something like jq -r . Commented Jan 30, 2022 at 0:15

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.