Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

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"]
like image 363
Vijay Boyapati Avatar asked Mar 20 '14 00:03

Vijay Boyapati


People also ask

How do I write a JSON file in Perl?

JSON FunctionsConverts the given Perl data structure to a json string. Expects a json string and tries to parse it, returning the resulting reference. Use this function with true value so that Perl can use TO_JSON method on the object's class to convert an object into JSON.

Can you put arrays in JSON?

Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.

How do I create an array of hashes in Perl?

To add another hash to an array, we first initialize the array with our data. Then, we use push to push the new hash to the array. The new hash should have all of its data. As shown below, you can see the difference between the two arrays before and after pushing a new hash.

What is encode in JSON?

In PHP the json_encode() function is used to encode a value to JSON format. The value being encoded can be any PHP data type except a resource, like a database or file handle.


1 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"]
like image 176
Miller Avatar answered Oct 19 '22 06:10

Miller