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"
        },
        "friends":
                [
                        {
                                "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
Alice
Laura
Daniel

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.

5 thoughts on “How to parse JSON string in Perl

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

    my $test = '{
    "name":"Tony",
    "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 = '{
         "name":"Tony",
         "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";
                  }
              } 
          } 
          
          hands:fingers
          muscles:biceps
          fingers:nails
          knuckles:sharp
          

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

        • 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);
          ...

Leave a comment

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

Current day month ye@r *