Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Iterate JSON File

by VinsWorldcom (Prior)
on Aug 02, 2018 at 16:52 UTC ( [id://1219719]=note: print w/replies, xml ) Need Help??


in reply to Iterate JSON File

Probably not the best way, but this works:

#!perl use strict; use warnings; use JSON::PP; my $json; { local $/ = undef; open my $fh, '<', 'in.json'; $json = <$fh>; close $fh; } my $final; my $decoded = decode_json($json); for my $ob ( @{$decoded->{observations}} ) { for my $status ( @{$ob->{status}} ) { for my $elem ( sort ( keys ( %{$status} ) ) ) { print $elem . "=" . $status->{$elem} . "\n"; } print "\n"; } }

and outputs ...

info=%(MinorFrameCnt)% kind=I path=_L7= stat=O info=%(Offset)% kind=I path=_L2= stat=O info=%(Period)% kind=I path=_L1= stat=O info=%(_L3)% = _L8 kind=I path=_L6=-1 stat=O info=_L3 = %(_L8)% kind=I path=_L6=-2 stat=O

Replies are listed 'Best First'.
Re^2: Iterate JSON File
by mijares93 (Initiate) on Aug 03, 2018 at 14:28 UTC

    Thank you for you answer, actually it worked great

    But now i want to only search for the "kind" tag and here is what i did:

    for my $ob ( @{$decoded->{observations}} ) { for my $status ( @{$ob->{status}} ) { for my $kind (@{$status->{info}}){ for $elem ( sort ( keys ( %{$kind} ) ) ) { $final1 .= $kind->{$elem} .","; } } } }

    I am getting an error that says that Cant use string (...) as an ARRAY ref while "stricts refs" in use at...

    I think that is something related to deference, but i am not sure how to solve it, could you help me?

    Regards

      You seem to think that  $kind is a hash reference, but it isn't; it's a string, and strings (a.k.a. "symbolic references") can't be dereferenced under strict 'refs'. It's important to know the nature of the data you're dealing with. To visualize the type and value (update: and structure!) of data, use a module like Data::Dumper (which is core, so it should already be installed), or Data::Dump (which I like more, but which is not core). So maybe something like

      use Data::Dumper; ... for my $kind (@{$status->{info}}){ print Dumper $kind; ... }
      to get started. Once you know where you are, it will be easier to see the way forward.


      Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1219719]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2024-04-19 13:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found