JSON Pure Perl Pretty Print

TL;DR

Something I reimplement over and over.

You might say: use a module, Fluke! You’re probably right.

Although… we’re talking JSON::PP here, which is in CORE since some time now:

JSON::PP was first released with perl v5.13.9

So… using a module tastes like betrayal.

Anyway.

I like readable and consistent JSON output, so here’s what I often go for:

use JSON::PP 'decode_json'; # no encode_json
sub encode_json {
    state $encoder = JSON::PP->new->utf8->canonical->pretty;
    return $encoder->encode($_[0]);
}

Trial run:

say encode_json({c => [1..3], a => 3});
# {
#    "a" : 3,
#    "c" : [
#       1,
#       2,
#       3
#    ]
# }

Function encode_json above serves as a drop-in replacement for the same-named function that might be but is not imported while useing the module here.

Option canonical tells the encoder to sort keys in objects/hashes, while pretty gets us some nicely indented output.

So there you go, a nice JSON pretty-printer in CORE!


Comments? Octodon, , GitHub, Reddit, or drop me a line!