Json in Perl

Here’s the translation of the JSON example from Go to Perl, formatted in Markdown suitable for Hugo:

Our first program will demonstrate JSON encoding and decoding in Perl. Here’s the full source code:

#!/usr/bin/env perl

use strict;
use warnings;
use JSON;
use Data::Dumper;

# We'll use these two hashes to demonstrate encoding and
# decoding of custom types below.
my $response1 = {
    Page   => 1,
    Fruits => ["apple", "peach", "pear"]
};

my $response2 = {
    page   => 1,
    fruits => ["apple", "peach", "pear"]
};

# First we'll look at encoding basic data types to
# JSON strings. Here are some examples for atomic values.
my $json = JSON->new->utf8;

my $bolB = $json->encode(1);
print "$bolB\n";

my $intB = $json->encode(1);
print "$intB\n";

my $fltB = $json->encode(2.34);
print "$fltB\n";

my $strB = $json->encode("gopher");
print "$strB\n";

# And here are some for arrays and hashes, which encode
# to JSON arrays and objects as you'd expect.
my $slcD = ["apple", "peach", "pear"];
my $slcB = $json->encode($slcD);
print "$slcB\n";

my $mapD = { apple => 5, lettuce => 7 };
my $mapB = $json->encode($mapD);
print "$mapB\n";

# The JSON module can automatically encode your
# custom data types.
my $res1B = $json->encode($response1);
print "$res1B\n";

my $res2B = $json->encode($response2);
print "$res2B\n";

# Now let's look at decoding JSON data into Perl
# values. Here's an example for a generic data structure.
my $byt = '{"num":6.13,"strs":["a","b"]}';

# We need to provide a variable where the JSON
# module can put the decoded data. This will be a
# hash reference in Perl.
my $dat = $json->decode($byt);
print Dumper($dat);

# In order to use the values in the decoded hash,
# we can directly access them. For example here we
# access the value in 'num'.
my $num = $dat->{num};
print "$num\n";

# Accessing nested data is straightforward in Perl.
my $str1 = $dat->{strs}[0];
print "$str1\n";

# We can also decode JSON into custom data types.
my $str = '{"page": 1, "fruits": ["apple", "peach"]}';
my $res = $json->decode($str);
print Dumper($res);
print $res->{fruits}[0], "\n";

# In Perl, we can directly print JSON to STDOUT.
my $d = { apple => 5, lettuce => 7 };
print $json->encode($d), "\n";

To run the program, save it as json.pl and use perl:

$ perl json.pl
true
1
2.34
"gopher"
["apple","peach","pear"]
{"apple":5,"lettuce":7}
{"Page":1,"Fruits":["apple","peach","pear"]}
{"page":1,"fruits":["apple","peach","pear"]}
$VAR1 = {
          'num' => '6.13',
          'strs' => [
                      'a',
                      'b'
                    ]
        };
6.13
a
$VAR1 = {
          'page' => 1,
          'fruits' => [
                        'apple',
                        'peach'
                      ]
        };
apple
{"apple":5,"lettuce":7}

We’ve covered the basics of JSON in Perl here. For more information, check out the documentation for the JSON module on CPAN.