serialization intermediate

How to use JSON::XS for faster JSON parsing in Perl?

Question

How to use JSON::XS for faster JSON parsing in Perl?

The JSON::XS module is a fast, C-based JSON encoder and decoder well-known for high performance and correct JSON handling in Perl. It significantly outperforms pure Perl solutions like JSON::PP and is ideal when speed is a priority.

Correcting the Common Interpolation Pitfall

The error in the previous code stems from unintended interpolation inside double-quoted strings. In Perl, the sigil @ triggers array interpolation inside double quotes, so a string like "alice@example.com" mistakenly tries to interpolate the array @example, which is undefined.

To fix this, either:

  • Use single quotes for strings containing @, e.g., 'alice@example.com'
  • Escape the @ as \@ inside double quotes

Below is the corrected example with single quotes around email strings to avoid interpolation errors.

Runnable Example Using JSON::XS

use strict;
use warnings;
use JSON::XS;

# Create a JSON::XS object with UTF-8 and pretty printing enabled
my $json = JSON::XS->new->utf8->pretty(1);

# Perl data structure with various types
my $data = {
    name    => 'Alice',
    age     => 30,
    emails  => ['alice@example.com', 'a.smith@example.org'],  # single quotes prevent interpolation
    active  => \1,       # boolean true in JSON::XS
    scores  => [88, 92, 75],
};

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

# Decode JSON string back to Perl data structure
my $decoded = $json->decode($json_text);

print "Decoded Perl data:\n";
print "Name: $decoded->{name}\n";
print "First email: $decoded->{emails}[0]\n";

# Dereference boolean reference safely
print "Active? " . (${$decoded->{active}} ? "Yes" : "No") . "\n";

Explanation of Perl Concepts

  • 'single quotes' prevent variable or array interpolation, avoiding errors with special characters like @.
  • JSON::XS->new creates a JSON encoder/decoder object.
  • utf8 ensures proper UTF-8 encoding/decoding.
  • pretty(1) formats JSON output with indentations.
  • JSON booleans are represented as scalar refs to 1 or 0, so dereference to check their value.

Common Pitfalls

  • Using double quotes with strings containing @ can cause "Global symbol" errors due to unintended array interpolation.
  • Always check boolean values decoded from JSON::XS by dereferencing scalar refs.
  • Remember to use strict; and warnings; to catch subtle bugs early.

Perl Version

JSON::XS is compatible with Perl 5.8 and newer. Improvements in Unicode handling make Perl 5.10+ preferable for utf8 JSON.

Summary

To use JSON::XS correctly, pay careful attention to Perl string quoting rules to avoid interpolation errors, especially when emails or other strings include @ signs. Using single-quoted strings for such content and knowing how JSON::XS handles booleans will make your JSON handling both fast and robust.

Verified Code

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

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Encoded JSON:
{
   "emails" : [
      "alice@example.com",
      "a.smith@example.org"
   ],
   "scores" : [
      88,
      92,
      75
   ],
   "age" : 30,
   "active" : true,
   "name" : "Alice"
}

Decoded Perl data:
Name: Alice
First email: alice@example.com
Active? Yes
STDERR
(empty)

Was this helpful?

Related Questions