in reply to parse json
Here's an example based on Mojo::JSON to get you started. Since I don't have access to the API you're using I've saved the example JSON to a file and slurped it in. You can use this as the guts of a program and simply chain the whole thing from a Mojo::UserAgent call to the API (e.g. $ua->get( .... )->result->json..), that way you don't need to worry about all the file reading business. Consider this an imperfect starting point:
#!/usr/bin/perl use strict; use warnings; use feature 'say'; use Mojo::File qw(path); use Mojo::JSON qw(decode_json); # Path to your JSON file my $file = path('yay_sports.json'); # Slurp and decode JSON my $json = decode_json( $file->slurp ); # Loop through each match for my $match ( @{$json->{response}} ){ # match status my $status = $match->{fixture}{status}{long}; # team names my $home = $match->{teams}{home}{name}; my $away = $match->{teams}{away}{name}; # half time my $ht_home = $match->{score}{halftime}{home} // 'N/A'; my $ht_away = $match->{score}{halftime}{away} // 'N/A'; # full time my $ft_home = $match->{score}{fulltime}{home} // 'N/A'; my $ft_away = $match->{score}{fulltime}{away} // 'N/A'; # output, may want to consider not printing if things haven't # happend yet, where FT shows N/A for example say "Match: $home vs $away"; say "Status: $status"; say "Halftime Score: $home $ht_home - $ht_away $away"; say "Fulltime Score: $home $ft_home - $ft_away $away"; say "-" x 40; }
Output:
Match: Sortland vs B�rum Status: First Half Halftime Score: Sortland 0 - 0 B�rum Fulltime Score: Sortland N/A - N/A B�rum ---------------------------------------- Match: Gal�cia U20 vs Jacuipense U20 Status: Halftime Halftime Score: Gal�cia U20 1 - 2 Jacuipense U20 Fulltime Score: Gal�cia U20 N/A - N/A Jacuipense U20 ----------------------------------------
There are some obvious issues I'm sure can see from the output, I'll leave them for you to address. Consider not jumping around from different sets of modules/frameworks if you don't have to. Mojolicious is very powerful, self contained and has everything you need to request and serve this content in a sane modern way.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: parse json
by joyfedl (Acolyte) on Jul 12, 2025 at 17:30 UTC |