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);
perl demo.pl
{
"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:
use strict; use warnings; use JSON::PP; my $text = '{"name":"Ada","tags":["perl","math"]}'; my $obj = JSON::PP->new->decode($text); print $obj->{name}, "\n"; print $obj->{tags}[1], "\n";
perl demo.pl
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:
use strict; use warnings; use JSON::PP; my $text = '{"name": }'; my $cfg = eval { JSON::PP->new->decode($text) }; if ($@) { die "bad JSON: $@"; }
perl demo.pl
bad JSON: malformed JSON string, neither array, object, number, string or atom, at character offset 9 (before "}") at demo.pl line 6.
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:
use strict; use warnings; use JSON::PP; open my $out, ">:raw", "config.json" or die "cannot write config.json: $!\n"; print $out '{"name":"Ada","port":8080}'; close $out or die "cannot close config.json: $!\n"; open my $fh, "<:raw", "config.json" or die "cannot read config.json: $!\n"; my $text = do { local $/; <$fh> }; my $cfg = JSON::PP->new->decode($text); print $cfg->{name}, " ", $cfg->{port}, "\n";
perl demo.pl
Ada 8080
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.
use strict; use warnings; use JSON::PP; my $cfg = { name => "Ada", port => 8080 }; my $json = JSON::PP->new->utf8->canonical->pretty; 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"; print "wrote config.json\n";
perl demo.pl
wrote config.json
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.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Since which Perl release does JSON::PP ship with the interpreter?
Answer
5.14
The module is in the core from 5.14, so a first JSON script needs no install.
-
What does the
canonicalsetting of JSON::PP do?Answer
It sorts the object keys, so the same data always produces the same text
A Perl hash has no order, and the setting makes the encoded text stable for diffs and checksums.
-
What does the
prettysetting do?Answer
It adds indentation for a human reader
The output spans several lines with spaces after the colons, which is for people and not for machines.
-
What does the
utf8setting do on the way out?Answer
It writes UTF-8 bytes instead of a character string
The setting decides who does the conversion: with utf8 the encoder writes the bytes, so the file handle must not decode again.
-
How do you read a JSON config file before decoding it?
Answer
Slurp it with
local $/in a block, so the whole file is one stringA JSON document is one value, and a line loop would hand the decoder a fragment of it.
-
What does a JSON
truebecome afterdecode?Answer
A blessed JSON::PP::Boolean object that is true in boolean context
The object keeps the distinction the encoder needs, and it is true or false in a condition.
-
What does this program print?
use JSON::PP; my $json = JSON::PP->new->canonical; print $json->encode({ b => 2, a => 1 }), "\n";Answer
{"a":1,"b":2}
Canonical sorts the keys, and without pretty the encoder writes the compact form.
-
What does this program print?
use JSON::PP; my $obj = JSON::PP->new->decode('{"tags":["perl","math"]}'); print $obj->{tags}[1], "\n";Answer
math
The decoder turns the array into an array reference, and the second element is math.
-
What does this program print?
use JSON::PP; my $json = JSON::PP->new->canonical; print $json->encode({ active => JSON::PP::true }), "\n";Answer
{"active":true}
The blessed true object encodes as the JSON literal, which a receiver expecting a boolean needs.
-
What does this program print?
use JSON::PP; my $obj = JSON::PP->new->decode('{"deleted":false}'); print $obj->{deleted} ? "yes\n" : "no\n";Answer
no
The decoded false object is false in boolean context, while it still encodes back as false.
Article author: Arthur Isaev