【问题标题】:Perl decoding json and get valuePerl解码json并获取值
【发布时间】:2021-10-13 08:09:51
【问题描述】:

我是 perl 新手,在解码 json 时需要帮助。

来自 url 的 json 输出

{
    "result": [
        {
            "manager": {
                "value": "testvalue",
                "data": "testdata"
            }
        }
    ]
}
my $decoded = decode_json($client->responseContent());

print  Dumper($decoded->{'result'}['manager']);

这将打印在下面。

$VAR1 = {
      'manager' => {
                     'value' => 'testvalue',
                     'data' => 'testdata'
                   }
    };

如何在变量中获取testvalue。?我尝试了不同的方法但无法破解

【问题讨论】:

  • 当您发布问题时,请附上您尝试过的代码,而不仅仅是“我尝试了不同的方式”。
  • print $decoded->{result}[0]{manager}{value}

标签: json perl


【解决方案1】:

这个说法是错误的:

print  Dumper($decoded->{'result'}['manager']);

因为您没有打开警告,这是一件非常糟糕的事情,所以您不会收到错误

Argument "manager" isn't numeric in array element at ...

您正在使用方括号[ .. ],这意味着Perl 期望它里面的内容是一个数组索引,一个数字。你放一个字符串。 Perl 会自动尝试将字符串转换为数字,但会警告您。除非你愚蠢地关闭了警告。任何不以数字开头的字符串都被转换为0,因此它将尝试访问数组元素0,如下所示:

print  Dumper($decoded->{'result'}[0]);

这正是您在 Dumper 输出中看到的内容:

$VAR1 = {
      'manager' => {
                     'value' => 'testvalue',
                     'data' => 'testdata'
                   }
    };

您需要做的是从键'value' 中的键'manager' 的哈希值中获取值,在存储在键'result' 中的哈希的第一个数组元素中:

print $decoded->{'result'}[0]{'manager'}{'value'}

可以很方便的遍历json结构看到Perl结构,看起来差不多。

{                                       # hash
    "result": [                         # key "result", stores array [
        {                                 # hash
            "manager": {                  # key "manager", stores hash {
                "value": "testvalue",        # key "value", value "testvalue"
                "data": "testdata"           # key "data", value "testdata"
            }
        }
    ]
}

总是把它放在你的 Perl 代码中:

use strict;
use warnings;

为了避免犯简单的错误或隐藏严重错误。

【讨论】:

    【解决方案2】:
    use strict;
    use warnings;
    use Carp;
    use English qw( -no_match_vars );
    
    # ...
    
    my $decoded;
    
    my $status = eval {
        $decoded = decode_json( $client->responseContent() );
        1;
    };
    
    if ( !$status || $EVAL_ERROR ) {
        croak 'some goes wrong';
    }
    
    if (   ref $decoded ne ref {}
        || ref $decoded->{result} ne ref []
        || !scalar @{ $decoded->{result} }
        || ref $decoded->{result}->[0] ne ref            {}
        || ref $decoded->{result}->[0]->{manager} ne ref {}
        || !exists $decoded->{result}->[0]->{manager}->{value} )
    {
        croak 'wrong structure';
    }
    
    my $manager = $decoded->{result}->[0]->{manager}->{value};
    

    【讨论】:

    • 如果您解释 如何 回答问题以及 什么 它做了什么(类似于 TLP 在 his answer :这不仅仅是代码转储)。
    • 您应始终进行检查,以确保数据符合您的要求。否则,代码可能会在最不合时宜的时刻以最意想不到的方式射出。
    猜你喜欢
    • 2015-01-12
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    • 2015-11-14
    • 2012-04-12
    • 2014-01-19
    • 2011-12-18
    • 1970-01-01
    相关资源
    最近更新 更多