How to parse JSON string in Perl

Last updated on October 16, 2020 by Dan Nanni

If you need to parse a JSON-formatted string in Perl, you can use a Perl module called JSON. 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

If interested, you can check out other tutorials on parsing JSON string, such as using Python language or a Linux command line.

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal (Credit Card) or Bitcoin (1M161JGAkz3oaHNvTiPFjNYkeABox8rb4g).

Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.

Xmodulo © 2021 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean