How do I encode a simple array into JSON in Perl?

All the examples that I've seen of encoding objects to JSON strings in Perl have involved hashes. How do I encode a simple array to a JSON string?

use strict;
use warnings;
use JSON;
my @arr = ("this", "is", "my", "array");
my $json_str = encode_json(@arr);  # This doesn't work, produced "arrayref expected"

# $json_str should be ["this", "is", "my", "array"]

Answers


If you run that code, you should get the following error:

hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)

You simply need to pass a reference to your \@arr

use strict;
use warnings;

use JSON;

my @arr = ("this", "is", "my", "array");
my $json_str = encode_json(\@arr);  # This will work now

print "$json_str";

Outputs

["this","is","my","array"]

Need Your Help

CXF web service client: "Cannot create a secure XMLInputFactory"

web-services cxf woodstox

I am wrote and deployed a CXF web service into a Tomcat server using the instructions here. The web service deploys fine as I can see the WSDL file in a web browser.