Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Array of hashes?

by Anonymous Monk
on Jan 04, 2021 at 17:18 UTC ( [id://11126297]=perlquestion: print w/replies, xml ) Need Help??

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

I get the following as a JSON file. I thought it was an array of hashes, but apparently, it is not. How do I access it?

$VAR1 = [ { 'Lang4' => 'ok', 'Lang9' => 'well', 'Lang7' => undef, 'Lang6' => undef, }, { 'Lang4' => 'one', 'Lang9' => 'two', 'Lang7' => undef, 'Lang6' => undef, } ]

Do you have a good reference to spot the kind of datastructure I am in front of (for a non-Perl expert). Thank you

Replies are listed 'Best First'.
Re: Array of hashes?
by haukex (Archbishop) on Jan 04, 2021 at 17:25 UTC
    I thought it was an array of hashes, but apparently, it is not. How do I access it?

    It is in fact an array of hashes, but I suspect the confusion might be coming from the fact that it's a reference to an array of hashes, as indicated by the square brackets [...]. In other words, $VAR1 here is a reference to an array, and the elements of that array are the hashes. You can access it like any reference to an array, i.e. $VAR1->[0]{Lang9} is 'well'. See perldsc, perlreftut, and perlref.

    Note that you haven't shown your code, but in case it looks like print Dumper(@array);, then I would guess that you're probably doing something like my @array = decode_json(...);, which isn't quite correct, as decode_json functions typically don't return an array, but instead a reference to an array or a hash. So in other words, you should be doing my $arrayref = decode_json('[...]');, and then use the dereferencing operators that are described in the links above - for example, for my $elem (@$arrayref) or my $first = $arrayref->[0];.

    Edit: Added a little bit more info to first sentence.

      Thank you. I read the json data like this (verbose here):

      my $data = decode_json( $json ); my $definition= $data->{'myData'}; my @definition=@$definition; print Dumper \@definition; #trying to access the data structure with: foreach my $record (@definition) { print $record->{Lang4}; }

      The json data is produced like this (according to documentation). I could access/change the script originating the json file, if needed:

      while (my $row = $sth->fetchrow_hashref) { push @definition, $row; } print objToJson( { myData => \@definition} );
        I read the json data like this

        That code works for me (Update: assuming the code you showed in the parent node is what produced the output shown in the root node). Please show a representative Short, Self-Contained, Correct Example that reproduces the problem you're having and that includes sample input, expected output, and actual output including any error messages (How do I post a question effectively?).

        use warnings; use strict; use Data::Dumper; use JSON::PP qw/decode_json/; my $json = <<'JSON'; { "myData" : [ { "Lang4":"ok", "Lang9":"well", "Lang7":null, "Lang6":null }, { "Lang4":"one", "Lang9":"two", "Lang7":null, "Lang6":null } ] } JSON my $data = decode_json( $json ); my $definition= $data->{'myData'}; my @definition=@$definition; print Dumper \@definition; foreach my $record (@definition) { print $record->{Lang4}, "\n"; }

        Output:

        $VAR1 = [ { 'Lang6' => undef, 'Lang9' => 'well', 'Lang4' => 'ok', 'Lang7' => undef }, { 'Lang6' => undef, 'Lang9' => 'two', 'Lang7' => undef, 'Lang4' => 'one' } ]; ok one
Re: Array of hashes?
by 1nickt (Canon) on Jan 04, 2021 at 18:22 UTC

    Hi,

    "Do you have a good reference to spot the kind of datastructure I am in front of"

    See perlreftut for a pretty good intro to the topic.

    Hope this helps!


    The way forward always starts with a minimal test.
Re: Array of hashes?
by Bod (Parson) on Jan 04, 2021 at 17:26 UTC
    I thought it was an array of hashes, but apparently, it is not.

    It looks like the output from Data::Dumper to me.

    We would need more information about where is came from or what you are trying to do with it to be able to help further.

      As OP said, it came as JSON, which would have looked exactly like this when received (other than perhaps ordering):

      [ { "Lang6" : null, "Lang7" : null, "Lang4" : "ok", "Lang9" : "well" }, { "Lang6" : null, "Lang7" : null, "Lang9" : "two", "Lang4" : "one" } ]

      This is one reason why JSON is so great. Translates into Perl data structures very cleanly. In fact, it translates into numerous programming language's data structures very cleanly. Cross-platform and cross-language data awesomeness.

      You can stringify it, and send it around, or even store it in a plain text file or database. Not so much with things like Data::Dumper or Storable.

      Observe:

      use warnings; use strict; use Data::Dumper; use JSON; my $jobj = JSON->new; my $json = '{"a": [1, 2], "b": {"a": 1, "b": 2}}'; print "Look Ma, a string of data!: $json\n\n"; my $perl = $jobj->decode($json); print Dumper $perl; print "\nConvert back from Perl to JSON string, and pretty print:\n"; print $jobj->pretty->encode($perl);

      Output:

      Look Ma, a string of data!: {"a": [1, 2], "b": {"a": 1, "b": 2}} $VAR1 = { 'a' => [ 1, 2 ], 'b' => { 'a' => 1, 'b' => 2 } }; Convert back from Perl to JSON string, and pretty print: { "a" : [ 1, 2 ], "b" : { "a" : 1, "b" : 2 } }

      Now, store it in a DB, send it to a client over the web, or open it up in a program written in Python or C# or whatever and stuff it into its native data structures.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11126297]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (3)
As of 2024-04-26 01:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found