How to read JSON file and parse it in Perl?

Question

How to read JSON file and parse it in Perl?

Perl handles JSON parsing through the JSON::PP module, which is included in the Perl core distribution since version 5.14. This module provides decode_json() to parse JSON strings into Perl data structures and encode_json() to convert Perl data back to JSON.

The basic workflow involves reading the file contents into a string, then parsing that string with decode_json(). JSON objects become Perl hash references, JSON arrays become array references, and JSON primitives map to their Perl equivalents.

Complete Example

#!/usr/bin/perl
use strict;
use warnings;
use JSON::PP;

# Simulate reading a JSON file by using inline JSON data
my $json_string = <<'END_JSON';
{
  "name": "John Doe",
  "age": 30,
  "email": "john@example.com",
  "skills": ["Perl", "Python", "JavaScript"],
  "active": true,
  "address": {
    "city": "New York",
    "zip": "10001"
  }
}
END_JSON

# Parse the JSON string
my $data = decode_json($json_string);

# Access the parsed data
print "Name: $data->{name}\n";
print "Age: $data->{age}\n";
print "Email: $data->{email}\n";
print "Skills: " . join(", ", @{$data->{skills}}) . "\n";
print "Active: " . ($data->{active} ? "Yes" : "No") . "\n";
print "City: $data->{address}{city}\n";
print "ZIP: $data->{address}{zip}\n";

Reading from an Actual File

When reading from a real file, you would use this pattern:

open my $fh, '<', 'data.json' or die "Cannot open file: $!";
my $json_string = do { local $/; <$fh> };
close $fh;
my $data = decode_json($json_string);

Common Pitfalls

  • UTF-8 encoding: Use open my $fh, '<:encoding(UTF-8)', 'file.json' for proper Unicode handling
  • Error handling: Wrap decode_json() in an eval block to catch malformed JSON
  • Boolean values: JSON booleans become JSON::PP::Boolean objects, not Perl 1/0
  • Module alternatives: JSON::XS is faster but requires compilation; JSON::PP is pure Perl and always available

The example above demonstrates accessing nested structures using Perl's arrow operator (->) and dereferencing arrays with @{}.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 26ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Name: John Doe
Age: 30
Email: john@example.com
Skills: Perl, Python, JavaScript
Active: Yes
City: New York
ZIP: 10001
STDERR
(empty)

Was this helpful?

Related Questions