Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

parse json

by frank1 (Monk)
on Sep 14, 2025 at 16:56 UTC ( [id://11166221]=perlquestion: print w/replies, xml ) Need Help??

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

i need some help on parsing some json msg, am doing a get request and getting the json output, but need help in parsing it and separating both teams with thier scores in declosed "competitors": {}, {}

this is my json output

{ "leagues": [ { "id": "700", "season": { "year": 2025, "type": { "id": "1", "type": 13481 } }, "logos": [ { "width": 500, "height": 500, "rel": [ "full", "default" ], "lastUpdated": "2019-05-08T16:07Z" }, { "width": 500, "height": 500, "rel": [ "full", "dark" ], "lastUpdated": "2021-08-10T20:43Z" } ], "calendarType": "day", "calendar": [ "2025-08-15T07:00Z" ] } ], "events": [ { "id": "740633", "season": { "year": 2025, "type": 13481 }, "competitions": [ { "id": "740633", "status": { "clock": 540, "displayClock": "9'", "period": 1, "type": { "id": "25", "shortDetail": "9'" } }, "venue": { "id": "197", "fullName": "Turf Moor", "address": { "country": "England" } }, "format": { "regulation": { "periods": 2 } }, "notes": [], "geoBroadcasts": [], "broadcasts": [], "broadcast": "", "competitors": [ { "id": "379", "homeAway": "home", "score": "0", "records": [ { "name": "All Splits" } ], "team": { "id": "379", "name": "Burnley", "links": [ { "rel": [ "clubhouse" ], "isHidden": false }, { "rel": [ "stats" ], "isHidden": false }, { "rel": [ "schedule" ], "isHidden": false }, { "rel": [ "squad" ], "isHidden": false } ], "venue": { "id": "197" } }, "statistics": [ { "name": "appearances" } ] }, { "id": "364", "homeAway": "away", "score": "0", "records": [ { "name": "All Splits" } ], "team": { "id": "364", "name": "Liverpool", "links": [ { "rel": [ "clubhouse" ], "isHidden": false }, { "rel": [ "stats" ], "isHidden": false }, { "rel": [ "schedule" ], "isHidden": false }, { "rel": [ "squad" ], "isHidden": false } ], "venue": { "id": "192" } }, "statistics": [ { "name": "appearances" } ] } ], "details": [], "odds": [ { "provider": { "id": "2000" }, "awayTeamOdds": { "summary": "1/3", "team": { "id": "364" }, "link": { "language": "en-GB", "rel": [ "away" ], "isHidden": false } }, "homeTeamOdds": { "summary": "8/1", "team": { "id": "379" }, "link": { "language": "en-GB", "rel": [ "home" ], "isHidden": false } }, "drawOdds": { "summary": "4/1", "link": { "language": "en-GB", "rel": [ "draw" ], "isHidden": false } } } ], "wasSuspended": false, "playByPlayAvailable": true, "playByPlayAthletes": true } ], "status": { "clock": 540, "displayClock": "9'", "period": 1, "type": { "id": "25", "shortDetail": "9'" } }, "venue": { "displayName": "Turf Moor" }, "links": [ { "language": "en-GB", "rel": [ "live" ], "isHidden": false }, { "language": "en-GB", "rel": [ "stats" ], "isHidden": false } ] } ] }

this is my part of script i want to fix, and output all teams with the scores

for my $match (@{$parse_json->{leagues}}) { my $elapsed = $match->{competitions}{status}{displayClock}; my $status = $match->{wasSuspended}; my $home = $match->{competitors}{team}{homeAway}; my $away = $match->{competitors}{team}{homeAway}; my $away_goal = $match->{competitors}{score}; my $home_goal = $match->{competitors}{score}; print "$elapsed: $home: $home_goal: Suspended Match: $status"; print "$elapsed: $away: $away_goal: Suspended Match: $status"; }

Replies are listed 'Best First'.
Re: parse json
by Corion (Patriarch) on Sep 14, 2025 at 17:53 UTC

    Please explain to us where you are having problems and where the code you have deviates from your expectations.

    If your script does not print what you expect, consider that ->{competitions} and ->{competitors} are arrays.

    Putting the use strict; pragma at the top of your code allows Perl to tell you where you are going wrong.

      this is my code below, am getting the results very well, my problem is parsing them, i tried this -> coz of an array but still cant parse out the message

      #!/usr/bin/perl use strict; use warnings; use LWP::UserAgent; use HTTP::Request; use JSON; my $url = 'link'; my $ua = LWP::UserAgent->new( ssl_opts => { verify_hostname => 0 }, ); $ua->agent("MyApp/0.1"); my $req = HTTP::Request->new(GET => $url); my $response = $ua->request($req); my $parse_json = JSON::XS->new->decode ($response->content); if ($response->is_success) { for my $match (@{$parse_json->{leagues}}) { my $elapsed = $match->{events}->{competitions}->{status}{display +Clock}; my $status = $match->{events}->{competitions}->{wasSuspended}; my $home = $match->{events}->{competitors}->{team}; my $away = $match->{events}->{competitors}->{team}; my $away_goal = $match->{events}->{competitions}->{competitors}-> +{score}; my $home_goal = $match->{events}->{competitions}->{competitors}-> +{score}; print "$elapsed: $home: $home_goal: Suspended Match: $status"; print "$elapsed: $away: $away_goal: Suspended Match: $status"; } } else { print $response->decoded_content; print $response->status_line, "n"; }

        You must be getting some kind of error message. What is the error message?

        Also, compare, manually, your code to your data structure:

        my $elapsed = $match->{events}->{competitions}->{status}{displayCloc +k} # HASH HASH HASH HASH

        Your data structure has array elements, for example events is an array.

Re: parse json
by choroba (Cardinal) on Sep 14, 2025 at 22:28 UTC
    Adding to Corion's answer: try this instead.

    print $parse_json->{events}[0]{competitions}[0]{status}{displayClock};

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

      thanks i have got it working now, my reaming problem is only 1 to separate home and away team scores (results)

      teams results are in "competitors":[{}]

      "competitors":[ { "id":"379", "homeAway":"home", "score":"0", "records":[ { "name":"All Splits" } ], "team":{ "id":"379", "name":"Burnley", "links":[ { "rel":[ "clubhouse" ], "isHidden":false }, { "rel":[ "stats" ], "isHidden":false }, { "rel":[ "schedule" ], "isHidden":false }, { "rel":[ "squad" ], "isHidden":false } ], "venue":{ "id":"197" } }, "statistics":[ { "name":"appearances" } ] }, # Here is next curly braces for away team { "id":"364", "homeAway":"away", "score":"3", "records":[ { "name":"All Splits" } ], "team":{ "id":"364", "name":"Manchester City", "links":[ { "rel":[ "clubhouse" ], "isHidden":false }, { "rel":[ "stats" ], "isHidden":false }, { "rel":[ "schedule" ], "isHidden":false }, { "rel":[ "squad" ], "isHidden":false } ], "venue":{ "id":"192" } }, "statistics":[ { "name":"appearances" } ] } ],

      Now i need some magic to separate curly braces for each team results and output this

      90'+7': Burnley scored 0 status: 0 90'+7': Manchester City scored 3 status: 0

      This is my working code

      for my $match (@{$parse_json->{'events'}}) { my $elapsed = $match->{competitions}[0]{status}{displayClock}; my $status = $match->{competitions}[0]{wasSuspended}; # 0 false +/ 1 true | "wasSuspended":false, my $home = $match->{competitions}[0]{competitors}[0]{'team'}{n +ame}; my $away = $match->{competitions}[0]{competitors}[0]{'team'}{n +ame}; my $home_score = $match->{competitions}[0]{competitors}[0]{score}; my $away_score = $match->{competitions}[0]{competitors}[0]{score}; print "$elapsed: $home scored $home_score status: $status"; }

        Is the home team always listed first, and the away team second?

        The second element of an array is at index position 1.

        So maybe

        my $home = $match->{competitions}[0]{competitors}[0]{'team'}{n +ame}; my $away = $match->{competitions}[0]{competitors}[1]{'team'}{n +ame}; my $home_score = $match->{competitions}[0]{competitors}[0]{score}; my $away_score = $match->{competitions}[0]{competitors}[1]{score};


        The way forward always starts with a minimal test.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2025-12-15 15:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your view on AI coding assistants?





    Results (95 votes). Check out past polls.

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.