in reply to how to acces data in JSON

use strict; use warnings; use Data::Dumper; use JSON; my $json = <<JSON; [ { "PROT_SIZE": "1620", "PROT_NAME": "ALK", "PROT_ID": "Q9UM73", "COVERTURA": [ { "PSTART": "1084", "PEND": "1405" }, { "PSTART": "1571", "PEND": "1589" } ] }, { "PROT_SIZE": "273", "PROT_NAME": "XPA", "PROT_ID": "P23025", "COVERTURA": [ { "PSTART": "67", "PEND": "77" }, { "PSTART": "98", "PEND": "210" } ] } ] JSON my $j = JSON->new->decode($json); for my $s (@$j) { next unless $s->{PROT_NAME} eq 'XPA'; for my $p (@{$s->{COVERTURA}}) { print $p->{PSTART},"\n"; } }

Replies are listed 'Best First'.
Re^2: how to acces data in JSON
by blue_cowdawg (Monsignor) on Apr 26, 2013 at 15:26 UTC

    damn... you came up with almost the same answer I did.. hate it when work interrupts my answering questions on Perl Monks. :-D


    Peter L. Berghold -- Unix Professional
    Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg
Re^2: how to acces data in JSON
by hulketa (Initiate) on Apr 28, 2013 at 14:13 UTC
    Thank you so much!! That's so useful!! But now I have a new problem. I'm completely begginer and I can't understand it. The problem is that I have to read the json file from my script. I've try like this:
    use strict; use warnings; binmode STDOUT, ":utf8"; use utf8; use JSON; my $json; { local $/; open my $fh, "<", "struc_cover_edu.json"; $json = <$fh>; close $fh; } my $j = JSON->new->decode($json); for my $s (@$j) { next unless $s->{PROT_NAME} eq 'XPA'; for my $p (@{$s->{COVERTURA}}) { print $p->{PSTART},"\n"; } }
    But an ERROR appears: Not an ARRAY reference at script.pl line 20. (line 20 is that one: for my $s (@$j) ) how could I solve it? thanks thanks thanks!!!

      Can you please put your code into code tags to make it more readible. Generally, such problems can be most easily analyzed with the module Data::Dumper. So add something like

      use Data::Dumper; ... print Dumper($j);

      to your code to see what is contained in $j. To be an array reference it has to be surrounded by square brackets [ ].