gezb has asked for the wisdom of the Perl Monks concerning the following question:

Hi, i'm trying to extract data from a json object but at a loss. I can see the perl data object via -d:ptkdb but cant reference the individual key, values. Both data dumps are the same. Any help would be appreciated. Thanks in advance

#!/usr/bin/env perl use strict; use Data::Dumper; use JSON; my $data = '[{"acc_id":0,"acc_cust_id":17,"acc_po_ref":"qwerty","acc_n +ame":"EX3000","acc_phonenum":"0121777777","acc_email":"ex3000@mail.co +m","acc_expires":null}]'; my @obj = from_json($data); my $obj = from_json($data); print Dumper(@obj)."\n"; print Dumper($obj)."\n"; $VAR1 = [ { 'acc_name' => 'EX3000', 'acc_po_ref' => 'qwerty', 'acc_expires' => undef, 'acc_email' => 'ex3000@mail.com', 'acc_id' => 0, 'acc_phonenum' => '0121777777', 'acc_cust_id' => 17 } ]; #print "$obj[0]{'acc_id'}\n"; #print "$obj[0]->{'acc_id'}\n";

Replies are listed 'Best First'.
Re: Extracting data from json object
by Corion (Patriarch) on Mar 21, 2014 at 08:08 UTC

    You are only accessing the element of @obj, never of $obj.

    The JSON structure contains a reference to an Array of Hashes already, so assining that to an array (@obj) makes things more complicated.

    If you assign the decoded JSON result to a scalar, $obj, then things Just Work:

    my $obj= from_json( $data ); print $obj->[0]->{acc_id};

    Using variables with the same name that differ only in the sigil is confusing.

Re: Extracting data from json object
by McA (Priest) on Mar 21, 2014 at 08:15 UTC

    Hi,

    one key point: The output of Data::Dumper should be valid Perl code, so you have the following snippet to interpret:

    $VAR1 = [ { 'acc_name' => 'EX3000', 'acc_po_ref' => 'qwerty', 'acc_expires' => undef, 'acc_email' => 'ex3000@mail.com', 'acc_id' => 0, 'acc_phonenum' => '0121777777', 'acc_cust_id' => 17 } ];

    Go from the outer to the inner of your construct. The variable $VAR is assigned a pair of square brackets, that means an array ref, in that is a pair of curly bracket, that means a hash ref. So you have a reference to an array having exactly one element (an hash(ref)). In that hash you have the expected assignments from key to value.

    Now to the derefencing. You have to get the first array element and from that tha value of a hash key:

    print $VAR->[0]->{'acc_name'};

    To remember: Decompose from the outer to the inner.

    McA