tags:

views:

97

answers:

2

Following perl code I have written to parse an array in JSON. 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
+5  A: 

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

Chas. Owens
Dereferencing helps a bit. Now I am able to iterate over the array returned. But still I get length of the array = 1
Niraj Nawanit
My bad. Was using length(@decoded_json) to get length of the array!!
Niraj Nawanit
A: 

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.

Tobi Oetiker