data beginner

How to use JSON module to encode and decode JSON

Question

How do I convert Perl data structures to JSON and parse JSON back to Perl?

The JSON module provides simple JSON encoding and decoding:

use strict;
use warnings;
use JSON;

my $json = JSON->new->utf8->pretty;

# Perl data structure
my $data = {
    name => 'Alice',
    age => 30,
    skills => ['Perl', 'Python', 'JavaScript'],
    active => \1,  # Boolean true
};

# Encode to JSON
my $json_text = $json->encode($data);
print "JSON output:\n$json_text\n";

# Decode from JSON
my $json_input = '{"name":"Bob","age":25,"city":"NYC"}';
my $decoded = $json->decode($json_input);

print "Decoded name: ", $decoded->{name}, "\n";
print "Decoded age: ", $decoded->{age}, "\n";
print "Decoded city: ", $decoded->{city}, "\n";

Output:

JSON output:
{
   "active" : true,
   "age" : 30,
   "name" : "Alice",
   "skills" : [
      "Perl",
      "Python",
      "JavaScript"
   ]
}
Decoded name: Bob
Decoded age: 25
Decoded city: NYC

The pretty method formats JSON with indentation for readability, and utf8 ensures proper Unicode handling.

Was this helpful?