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

Hi! I can sum my JSON data like this:
[ { "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" } ] } ]
and I would like to print the PSTART when the PROT_NAME was, for example, XPA. How can I acces to these data? Can anyone help me please?? Thanks!!

Replies are listed 'Best First'.
Re: how to acces data in JSON
by hdb (Monsignor) on Apr 26, 2013 at 15:09 UTC
    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"; } }

      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
      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 [ ].

Re: how to acces data in JSON
by Anonymous Monk on Apr 26, 2013 at 14:45 UTC