12

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"]
1
  • 1
    "This doesn't work" isn't a useful description of your problem. Please explain carefully what happens, and how it differs from what you require. Commented Mar 20, 2014 at 1:10

1 Answer 1

30

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"]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.