简体   繁体   English

Perl LWP::UserAgent 解析响应 JSON

[英]Perl LWP::UserAgent parse response JSON

I am using the LWP::UserAgent module to issue a GET request to one of our APIs.我正在使用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;

The request is successful.请求成功。 Dumper returns the following JSON. 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"
          }
      }';

Let's say I want to print the value of the apiVersion key, which should print v1 .假设我想打印 apiVersion 键的值,它应该打印v1

print "API Version = $request->content->{'apiVersion'} \n";

The following is being printed.正在打印以下内容。 I am not sure how to print the value v1 .我不确定如何打印值v1 Since HTTP::Response is included in the output, I suspect I might have to use the HTTP::Response module ?由于 HTTP::Response 包含在输出中,我怀疑我可能必须使用HTTP::Response 模块

API Version = HTTP::Response=HASH(0x2dffe80)->content->{'apiVersion'}

The JSON content must be decoded first.必须首先解码 JSON 内容。 There are several modules for that, like JSON :有几个模块,比如JSON

use JSON;
# ...
my $href = decode_json $request->content;

And then use it like a normal hash reference: $href->{apiVersion}然后像普通的哈希引用一样使用它: $href->{apiVersion}

Perl doesn't expand subroutine calls in a double-quoted string. Perl 不会在双引号字符串中扩展子例程调用。

 print "API Version = $request->content->{'apiVersion'} \\n";

In this line of code, content() is a subroutine call.在这行代码中, content()是一个子程序调用。 So Perl sees this as:所以 Perl 认为:

print "API Version = $request" . "->content->{'apiVersion'} \n";

And if you try to print most Perl objects, you'll get the hash reference along with the name of the class - hence HTTP::Response=HASH(0x2dffe80) .如果您尝试打印大多数 Perl 对象,您将获得散列引用以及类的名称 - 因此HTTP::Response=HASH(0x2dffe80)

You might think that you just need to break up your print() statement like this:你可能认为你只需要像这样分解你的print()语句:

print 'API Version = ', $request->content->{'apiVersion'}, "\n";

But that's not going to work either.但这也行不通。 $request->content doesn't return a Perl data structure, it returns a JSON-encoded string. $request->content不返回 Perl 数据结构,它返回一个 JSON 编码的字符串。 You need to decode it into a data structure before you can access the individual elements.您需要先将其解码为数据结构,然后才能访问各个元素。

use JSON;

print 'API Version = ', decode_json($request->content)->{'apiVersion'}, "\n";

But it might be cleaner to do the decoding outside of the print() statement.但是在print()语句之外进行解码可能会更清晰。

use JSON;

my $data = decode_json($request->content);

In which case you can go back to something more like your original code:在这种情况下,您可以返回更像原始代码的内容:

print "API Version = $data->{'apiVersion'} \n";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM