开发者

Parsing an array encoded in JSON through perl

开发者 https://www.devze.com 2023-01-16 00:57 出处:网络
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

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), leng开发者_运维问答th(@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.

0

精彩评论

暂无评论...
验证码 换一张
取 消