How to write Perl data structure to JSON file?

Question

How to write Perl data structure to JSON file?

How to Write a Perl Data Structure to a JSON File

Serializing Perl data structures to JSON format is a common task, especially when you need to exchange data with web services or store structured information in a file readable by other programs. JSON (JavaScript Object Notation) is a lightweight format that many programming languages understand, and Perl offers convenient modules to handle JSON encoding and decoding.

The most popular core module for working with JSON in Perl is JSON (since Perl 5.14+ it's commonly included, but you can install it from CPAN if needed). The JSON module provides easy methods to convert Perl data structures (hashes, arrays, scalars) into JSON text, which you can then write to a file.

Step-by-Step Solution

  • Prepare your Perl data structure: This can be a hashref, arrayref, or combination of both.
  • Encode the data structure to JSON string: Use the encode_json function or create a JSON object and call encode.
  • Write the JSON string to a file: Open the file for writing, print the JSON text, and close it.

Perl-specific Concepts

  • $scalar – a scalar variable, holds a single value.
  • @array – an array variable, holds an ordered list.
  • %hash – a hash variable, holds key/value pairs.
  • -> – dereference operator to access array or hash refs.
  • TMTOWTDI ("There's more than one way to do it") – you can encode JSON in different ways (procedural or OO interface).

Example: Write Perl Data Structure to JSON File

use strict;
use warnings;
use JSON;  # Core Perl module for JSON handling

# Example Perl data structure (a hashref containing arrayref and scalars)
my $data = {
    name    => "Alice",
    age     => 30,
    hobbies => ["reading", "hiking", "cooking"],
    address => {
        city  => "Springfield",
        state => "IL",
    },
};

# Create JSON encoder object with pretty print for readability
my $json = JSON->new->utf8->pretty;

# Encode Perl data structure to JSON string
my $json_text = $json->encode($data);

# Write JSON string to a file
my $filename = "output.json";
open my $fh, '>', $filename or die "Could not open '$filename' for writing: $!";
print $fh $json_text;
close $fh;

print "JSON data successfully written to $filename\n";

Explanation

In the above example:

  • The $data variable holds a nested Perl data structure using hash and array references.
  • JSON->new->utf8->pretty creates a JSON encoder object configured to output UTF-8 encoded and pretty-formatted JSON, which makes the output easier to read.
  • $json->encode($data) converts the Perl data into a JSON string.
  • The JSON string is written to output.json using a simple file open, print, and close sequence.

Common Pitfalls

  • Encoding non-UTF-8 data: Use the utf8 method on the JSON object to ensure proper UTF-8 output.
  • File handling: Always check for errors when opening files to avoid silent failures.
  • Complex data structures: Circular references or blessed references are not supported by default by JSON encoding.
  • Version considerations: If using older Perl (<5.14), ensure JSON module is installed via CPAN.

Overall, writing Perl data to JSON files is straightforward with the JSON module. This enables smooth interoperability with many tools and languages that consume JSON.

Verified Code

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

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
JSON data successfully written to output.json
STDERR
(empty)

Was this helpful?

Related Questions