Bonjour
Bonjour

Reputation: 23

Creating JSON in perl

Using this code, I am only getting an array of values name and extension listed one after the other, how do I get a separate {name:"tom", extension:"012345"} for each hash I am creating? i.e I would like [{name:"tom", extension:"012345"}, {name:"tim", extension:"66666"}]

#!/usr/bin/perl
use strict;
use warnings;
use lib $ENV{HOME} . '/perl/lib/perl5';
use lib '/home/accounts/lib';

use Data::Dump qw(dump);
use Lib::Phonebook;
use JSON;

my $ldap = Lib::Phonebook->new();
my (@names, @numbers, $count, $name_number_count, @result);

@names             = $ldap->list_telephone_account_names();
@numbers           = $ldap->list_telephone_account_numbers();
$name_number_count = @names;
$count = 0;

for $count (0 .. $name_number_count - 1) {
    my %hash = ( "name" => $names[$count], "extension" => $numbers[$count] );
    push( @result, %hash );
}

my $json = encode_json \@result;
print dump $json;

Upvotes: 0

Views: 243

Answers (1)

Leeft
Leeft

Reputation: 3837

Instead of

push( @result, %hash );

do:

push( @result, \%hash );

The original statement copies the entire hash to a list (as you discovered that becomes key, value, key, value, ...), whereas adding the backslash pushes a reference to the hash (without copying anything else) and serializing all that to JSON creates a nested structure.

Upvotes: 3

Related Questions