How to parse JSON string in Perl

If you need to parse a JSON-formatted string in Perl, you can use JSON Perl module. The JSON module contains JSON-specific decode/encode functions that convert a JSON string into a Perl data structure, and vice versa. Here is how to parse JSON string in Perl.

First, install JSON Perl module from CPAN:

$ sudo perl -MCPAN -e 'install JSON'

Alternatively, if you are using Ubuntu or Debian, you can install JSON module as follows.

$ sudo apt-get install libjson-pp-perl

You can then use a function called decode_json() which decodes a JSON string, and returns the reference to a corresponding Perl data structure.

The following Perl example shows how to parse JSON string, including JSON object and JSON array.

use strict;
use warnings;
use JSON qw( decode_json );

my $json = '{
        "name": "Bob",
        "sex": "Male",
        "address": {
                "city": "San Jose",
                "state": "California"
                                "name": "Alice",
                                "age": "20"
                                "name": "Laura",
                                "age": "23"
                                "name": "Daniel",
                                "age": "30"

my $decoded = decode_json($json);

# This is a Perl example of parsing a JSON object.

print "City = " . $decoded->{'address'}{'city'} . "\n";

# This is a Perl example of parsing a JSON array.

my @friends = @{ $decoded->{'friends'} };
foreach my $f ( @friends ) {
  print $f->{"name"} . "\n";

The above Perl code snippet will print out the following.

City = San Jose

Subscribe to Xmodulo

Do you want to receive Linux FAQs, detailed tutorials and tips published at Xmodulo? Enter your email address below, and we will deliver our Linux posts straight to your email box, for free. Delivery powered by Google Feedburner.

Support Xmodulo

Did you find this tutorial helpful? Then please be generous and support Xmodulo!

The following two tabs change content below.
Dan Nanni is the founder and also a regular contributor of He is a Linux/FOSS enthusiast who loves to get his hands dirty with his Linux box. He likes to procrastinate when he is supposed to be busy and productive. When he is otherwise free, he likes to watch movies and shop for the coolest gadgets.

7 thoughts on “How to parse JSON string in Perl

  1. How do I parse a 3D JSON array?

    my $test = '{
    "body":[ {
    "arms":["hands:fingers", "muscles:biceps"],
    "stomach":["abs:sixpack", "noabs:onepack"]
    "arms":["fingers:nails", "knuckles:sharp"],
    "stomach":["gut:beer", "liver:liquor"]

    I'm trying this and it isn't working:

    my $decoded = decode_json($test);
    my @layer1 = @{ $decoded->{'body'} };
    foreach ( @layer1 ) {
    @layer2 = $_->{$decoded->{'arms'} };
    foreach( @layer2 ) {
    print $_->{$decoded->{'hands'}} . "\n";

    I expect the printout to be: fingers

    • Your JSON string is malformed. It should be:

      my $test = '{
         "body": [ 
           { "arms": {"hands":"fingers", "muscles":"biceps" },
             "stomach": {"abs":"sixpack", "noabs":"onepack"} },
           { "arms": { "fingers":"nails", "knuckles":"sharp" },
             "stomach": {"gut":"beer", "liver":"liquor"} }
      • That's actually the format of the JSON returned from the website I'm pulling from... Is there no way to parse this? I know it's possible in Powershell because I'm converting a script written in Powershell to Perl so it can work on Linux. There HAS to be a way!

        • The best you can do is:

          my $decoded = decode_json($test);
          my @layer1 = @{$decoded->{'body'}};
          foreach (@layer1) {
              my @layer2 = $_->{'arms'};
              foreach (@layer2) {
                  my @layer3 = @{ $_ };
                  foreach (@layer3) {
                      print "$_\n";

          I don't think you can parse "hands:fingers" in JSON as this is a JSON string. Use regular expression instead.

        • The easiest approach for this mal-formed input is to use a regex to replace all square brackets with their corresponding curly brackets, and feed the resulting string into the JSON parser.

          $test =~ tr/[{/]}/;
          my $decoded = decode_json($test);

  2. What if I want to parse a file?

    I tried this below with no luck:

    my $json = '/home/vagrant/code/perl/json/friends.json';
    open(my $fh, '<:encoding(UTF-8)', $json)
    or die "Could not open file '$json' $!";

    my $decoded = decode_json($fh);

    I receive the following error:

    malformed JSON string, neither tag, array, object, number, string or atom, at character offset 0 (before "(end of string)”)


Leave a comment

Your email address will not be published. Required fields are marked *