in reply to Get element of array not looping.
syntax error at ./script.pl line 8, near ""facts":"
Perl can parse JSON, but only from a string, not directly from the source code. In Perl hashes, keys are separated by commas or fat commas from the values, not colons. Then, you can do:
my $DATA = { facts => [ { name => 'A', type => 'Normal' }, { name => 'B', type => 'Broken' } ], }; print $DATA->{facts}[0]{name}; # A print $DATA->{facts}[0]{type}; # Normal
It's a hash containing an array containing hashes, not a hash of hashes of arrays.
Or, parse the JSON, but remove the trailing comma after the array, JSON doesn't support it:
#!/usr/bin/perl use warnings; use strict; use Cpanel::JSON::XS; my $DATA = decode_json('{ "facts": [ { "name": "A", "type": "Normal" }, { "name": "B", "type": "Broken" } ] }'); print $DATA->{facts}[0]{name}; # A print $DATA->{facts}[0]{type}; # Normal
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Get element of array not looping.
by Anonymous Monk on Jul 13, 2021 at 18:58 UTC |