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

I have the following json message, am getting results, am getting 1 team instead of all, i want to get all teams

teams are enclosed by curly braces in

"teams":[ {}, #team {} # another team ],

{ "sports": [ { "id": "600", "leagues": [ { "id": "700", "teams": [ { "team": { "id": "331", "name": "Brighton & Hove Albion", "isAllStar": false, "logos": [ { "alt": "", "rel": [ "full", "default" ], "width": 500, "height": 500 }, { "alt": "", "rel": [ "full", "dark" ], "width": 500, "height": 500 } ], "links": [ { "language": "en-US", "rel": [ "clubhouse", "desktop", "team" ], "text": "Clubhouse" }, { "language": "en-US", "rel": [ "stats", "desktop", "team" ], "text": "Stats" }, { "language": "en-US", "rel": [ "schedule", "desktop", "team" ], "text": "Fixtures" } ] } }, { "team": { "id": "380", "name": "Wolverhampton Wanderers", "isAllStar": false, "logos": [ { "alt": "", "rel": [ "full", "default" ], "width": 500, "height": 500 }, { "alt": "", "rel": [ "full", "dark" ], "width": 500, "height": 500 } ], "links": [ { "language": "en-US", "rel": [ "clubhouse", "desktop", "team" ], "text": "Clubhouse" }, { "language": "en-US", "rel": [ "stats", "desktop", "team" ], "text": "Stats" }, { "language": "en-US", "rel": [ "schedule", "desktop", "team" ], "text": "Fixtures" } ] } } ], "year": 2025, "season": { "year": 2025, "displayName": "2025" } } ] } ] }

this is my code

for my $match (@{$parse_json->{sports}}) { my $teamname = $match->{leagues}[0]{teams}[0]{team}{name}; $Response_tmlist .= $teamname; print $Response_tmlist; }

Replies are listed 'Best First'.
Re: parse out json message
by 1nickt (Canon) on Sep 15, 2025 at 21:29 UTC

    What is the element you need to loop through to get the {team}{name} value? Is it sports? No. It's nested, at {sports}[0]{leagues}[0]{teams}. That's what you need to loop through. It's an arrayref, so you have to treat it like an array in your code.

    say $_->{team}{name} for @{ $parse_json->{sports}[0]{leagues}[0]{teams} };

    Please try to understand this before you use it in your code.


    The way forward always starts with a minimal test.

      thank you, its working now, thanks for explanation and demo

Re: parse out json message
by hippo (Archbishop) on Sep 15, 2025 at 16:50 UTC

    You are looping over sports when you want to be looping over teams.


    🦛

      i tried this and dont get anything out

      for my $match (@{$parse_json->{teams}}) {

        teams is not at the top level. You have at least leagues on your way into the data structure.

        Consider an online viewer like, say https://jsoncrack.com/editor or maybe https://jsonviewer.stack.hu/ to visualize the data structure.

        You have to learn to read JSON and how to translate that structure into Perl.