in reply to Consuming A Web Service
update: meh, I completely read right past where you said you wanted to process in XML. I digress.../update
As Corion mentioned, this is JSON, and is exceptionally common for web API returns. Here's how you can import it into a Perl structure and get at it.
use warnings; use strict; use Data::Dumper; use JSON::XS; my $json; { local $/; $json = <DATA>; } my $perl = decode_json $json; for my $href (@$perl){ print "vendor: $href->{Header}{VendorName}\n"; for my $item (@{ $href->{Items} }){ print "\track num: $item->{RackNumber}\n"; } } __DATA__ ...paste the JSON string here
output:
vendor: Some Business rack num: 3127824 rack num: 3127825 vendor: Some Business rack num: 3127828 rack num: 3128353 rack num: 3128796 rack num: 3128797
Now, a couple of notes. I'm going to rework it with your actual code, and explain what's happening. You don't need the special $/ block in your case, nor the __DATA__ section:
use warnings; use strict; use HTTP::Request::Common qw(GET); use JSON::XS; use LWP::UserAgent; my $ua = LWP::UserAgent->new; my $endpoint = 'http://blah'; my $req = HTTP::Request->new('GET'); $req->url($endpoint); my $resp = $ua->request($req); my $json = $resp->content; my $perl = decode_json $json; # it's an array of hashes of hashes (AoHoH). We need to # access it like this: for my $href (@$perl){ # grabbed each hash reference from the top-level array # ...now, print the vendor's name print "vendor: $href->{Header}{VendorName}\n"; for my $item (@{ $href->{Items} }){ # each top level href has a Header href, and many # Item hrefs inside of an array ref. Here, we're # looping over each Item, and doing something print "\track num: $item->{RackNumber}\n"; } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Consuming A Web Service
by pkupnorth (Novice) on Nov 02, 2016 at 16:52 UTC |