JSON with JSON::PP
Encoding data
JSON::PP ships with Perl since version 5.14, so no install is needed for your first JSON code. It turns a hash or array reference into text and back again.
use strict;
use warnings;
use JSON::PP;
my $data = {
name => "Ada",
tags => ["perl", "math"],
score => 42,
};
my $json = JSON::PP->new->utf8->canonical->pretty;
print $json->encode($data);
{ "name" : "Ada", "score" : 42, "tags" : [ "perl", "math" ] }
Each chainable setting has a purpose. utf8 makes the output UTF-8 bytes instead of a character string. canonical sorts object keys, which keeps diffs and checksums stable. pretty adds indentation for humans; drop it for anything a machine will parse.
Perl hashes have no order, so without canonical the same data can produce different text on every run. That surprises people who compare JSON strings in tests.
Decoding and errors
Decoding returns the same shape you encoded: objects become hash references, arrays become array references. From there it is ordinary Perl:
my $text = '{"name":"Ada","tags":["perl","math"]}';
my $obj = $json->decode($text);
print $obj->{name}, "\n";
print $obj->{tags}[1], "\n";
Ada math
Malformed input makes decode die with a message that names the byte offset. Catch it when the text comes from outside your program, so a bad request produces a clean error instead of a stack trace:
my $cfg = eval { $json->decode($text) };
if ($@) {
die "bad JSON: $@";
}
Always check the reference type you got back. A document that should be an object can legally be an array or a bare string, and indexing the wrong one fails at runtime rather than at parse time.
JSON files
A JSON config is one value, not a stream of lines, so read the whole file before decoding. local $/ sets the input separator to undef inside the block, which is the standard slurp idiom:
open my $fh, "<:raw", "config.json"
or die "cannot read config.json: $!\n";
my $text = do { local $/; <$fh> };
my $cfg = $json->decode($text);
Open with :raw and let ->utf8 do the decoding, or open with :encoding(UTF-8) and drop ->utf8. Doing both double-decodes the bytes and turns non-ASCII names into mojibake.
To write a file, encode first and print the bytes. Write to a temporary name and rename it into place when the data matters, so a crash halfway through cannot leave a truncated config behind.
open my $out, ">:raw", "config.json.new"
or die "cannot write: $!\n";
print $out $json->encode($cfg);
close $out or die "cannot close: $!\n";
rename "config.json.new", "config.json"
or die "cannot replace config.json: $!\n";
Booleans and numbers
Perl has no separate true and false values, so JSON::PP provides two objects that encode as the literals. Use them when the receiver expects a real boolean:
active => JSON::PP::true,
deleted => JSON::PP::false,
After decoding, those literals come back as blessed objects that are true and false in boolean context, so if ($obj->{active}) works. Comparing them with == 1 works too, but comparing the encoded text does not.
Numbers need care on the way out. Perl cannot always tell a string "42" from the number 42, and JSON can. If the distinction matters, force it with 0 + $value for numbers and "$value" for strings.
count => 0 + $count,
zip => "" . $zip,
Very large integers lose precision once they pass what a floating point number can hold exactly. Keep identifiers as strings, and reach for Math::BigInt only when you truly need arithmetic on them.
Next: HTTP clients with HTTP::Tiny
Article author: Arthur Isaev