【发布时间】:2021-12-01 15:03:34
【问题描述】:
我正在使用LWP::UserAgent 模块向我们的其中一个 API 发出 GET 请求。
#!/usr/bin/perl
use strict;
use warning;
use LWP::UserAgent;
use Data::Dumper;
my $ua = LWP::UserAgent->new;
my $request = $ua->get("http://example.com/foo", Authorization => "Bearer abc123", Accept => "application/json" );
print Dumper $request->content;
请求成功。 Dumper 返回以下 JSON。
$VAR1 = '{
"apiVersion": "v1",
"data": {
"ca-bundle.crt": "-----BEGIN CERTIFICATE-----abc123-----END CERTIFICATE-----\\n"
},
"kind": "ConfigMap",
"metadata": {
"creationTimestamp": "2021-07-16T17:13:01Z",
"labels": {
"auth.openshift.io/managed-certificate-type": "ca-bundle"
},
"managedFields": [
{
"apiVersion": "v1",
"fieldsType": "FieldsV1",
"fieldsV1": {
"f:data": {
".": {},
"f:ca-bundle.crt": {}
},
"f:metadata": {
"f:labels": {
".": {},
"f:auth.openshift.io/managed-certificate-type": {}
}
}
},
"manager": "cluster-kube-apiserver-operator",
"operation": "Update",
"time": "2021-09-14T17:07:39Z"
}
],
"name": "kube-control-plane-signer-ca",
"namespace": "openshift-kube-apiserver-operator",
"resourceVersion": "65461225",
"selfLink": "/api/v1/namespaces/openshift-kube-apiserver-operator/configmaps/kube-control-plane-signer-ca",
"uid": "f9aea067-1234-5678-9101-9d4073f5ae53"
}
}';
假设我想打印 apiVersion 键的值,它应该打印 v1。
print "API Version = $request->content->{'apiVersion'} \n";
正在打印以下内容。我不确定如何打印值 v1。由于 HTTP::Response 包含在输出中,我怀疑我可能必须使用 HTTP::Response module?
API Version = HTTP::Response=HASH(0x2dffe80)->content->{'apiVersion'}
【问题讨论】:
-
您应该首先使用例如将 JSON 字符串输出解析为 Perl 哈希。 JSON::XS。然后您可以在该哈希上使用语法:
$hash->{apiVersion}
标签: json perl curl httpresponse lwp-useragent