Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing an array encoded in JSON through perl

Tags:

json

perl

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
like image 385
Niraj Nawanit Avatar asked Sep 12 '10 14:09

Niraj Nawanit


2 Answers

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

like image 91
Chas. Owens Avatar answered Oct 23 '22 21:10

Chas. Owens


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.

like image 42
Tobi Oetiker Avatar answered Oct 23 '22 21:10

Tobi Oetiker