13

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

2 Answers 2

26

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

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.

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.