问题
Is there a way in perl to parse json response for the next curl request?
e.g.
I have a command:
curl -H "Content-Type: application/json" -H "Authorization: Bearer DS_12345" -X GET https://api.xxx
The response is:
{
"method":"a",
"users":["user@xxx.com "],
"status":"DONE",
"export-url":"https://api.xxx/v1/export/DP_6789xxx"
}
When (Wait until) the response includes "status":"DONE", instead of "FAIL" or "PROCESSING", run the next step by taking response "export-url":"https://api.xxx/v1/export/DP_6789xxx" from the previous step. When the status is "PROCESSING", I don't want to quit the program and run it again. Instead, I want to wait until the status is "DONE" and then go for the next step
curl -H "Content-Type: application/json" -H "Authorization: Bearer DS_12345" -X GET https://api.xxx/v1/export/DP_6789xxx?view=xml
I appreciate your time and help.
回答1:
No need to use curl. Use curl2lwp to translate your requests to Perl using LWP::UserAgent.
Use a library to parse JSON. Here, I used Cpanel::JSON::XS, but for simple stuff like this, any other should work as well.
#!/usr/bin/perl
use strict;
use warnings;
use LWP::UserAgent;
use Cpanel::JSON::XS;
my $ua = 'LWP::UserAgent'->new(send_te => 0);
my $req = 'HTTP::Request'->new(
GET => 'https://api.xxx/',
[
'Accept' => '*/*',
'Authorization' => 'Bearer DS_12345',
'Host' => 'api.xxx:443',
'User-Agent' => 'curl/7.55.1',
'Content-Type' => 'application/json',
],
);
my $res = $ua->request($req);
die $res->status_line unless $res->is_success;
my $response_structure = decode_json($res->decoded_content);
if ($response_structure eq 'DONE') {
my $req = 'HTTP::Request'->new(
GET => $response_structure->{'export-url'} . '?view=xml',
[
'Accept' => '*/*',
'Authorization' => 'Bearer DS_12345',
'Host' => 'api.xxx:443',
'User-Agent' => 'curl/7.55.1',
'Content-Type' => 'application/json',
],
);
my $res = $ua->request($req);
...
}
来源:https://stackoverflow.com/questions/60650821/perl-parse-json-response-for-next-curl-request