I am using the Following Perl code to parse an array in JSON, using the JSON
module. But the array returned has length 1 and I am not able to iterate over it properly. So the problem is I am not able to use the array returned.
#!/usr/bin/perl
use strict;
my $json_text = '[ {"name" : "abc", "text" : "text1"}, {"name" : "xyz", "text" : "text2"} ]';
use JSON;
use Data::Dumper::Names;
my @decoded_json = decode_json($json_text);
print Dumper(@decoded_json), length(@decoded_json), "\n";
The output comes :
$VAR1 = [
{
'text' => 'text1',
'name' => 'abc'
},
{
'text' => 'text2',
'name' => 'xyz'
}
];
1
The decode_json
function returns an arrayref, not a list. You must dereference it to get the list:
my @decoded_json = @{decode_json($json_text)};
You may want to read perldoc perlreftut
and perldoc perlref
Regarding JSON, you may want to make sure you install the JSON::XS
module as it is faster and more stable than the pure Perl implementation included with the JSON
module. The JSON
module will use JSON::XS
automatically when it is available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With