2017-07-25 11 views
0

こんにちはすべて私はperlで新しいですが、私は他の言語での経験はほとんどありません。 私はここで電信ボットのインターネットからJSONファイルを取得するシンプルなコードを作ったが、私はそれを表示しても何の問題もなかったが、デコードコードでデコードしたときには同じ出力を持っていなかった:///要求は同じではないデコード

ここでは、サーバの出力:

Received reply: {"ok":true,"result":{"id":0000,"first_name":"[MAGA]"}} 

、今デコードanwserの出力:

$VAR1 = { 
     'ok' => bless(do{\(my $o = 1)}, 'JSON::PP::Boolean'), 
     'result' => { 
        'id' => 0000, 
        'username' => 'MAGA_bot', 
        'first_name' => '[MAGA]' 
        } 
    }; 

は、どのように私はちょうど復号化されたJSONの「結果」の部分を得ることができますか?

ここに私のコード:

#!/usr/bin/perl 

use warnings; 

use LWP::UserAgent; 
use Data::Dumper; 
use JSON; 

my $ua = LWP::UserAgent->new; 

my $destination = "http://api.telegram.org/bot<TOKEN>/getMe"; 

my $req = HTTP::Request->new(GET => $destination); 
my $succes; 
my $json; 

my $resp = $ua->request($req); 
if ($resp->is_success) { 
    my $message = $resp->decoded_content; 
    print "Received reply: $message\n"; 
    $succes = "yes"; 
    $json = $message; 
} else { 
    print "HTTP POST error code: ", $resp->code, "\n"; 
    print "HTTP POST error message: ", $resp->message, "\n"; 
} 

print "Encoding the JSON file \n"; 
if ($succes eq "yes") { 
    my $decoded_json = decode_json($json); 
    print Dumper($decoded_json); 
} elsif ($succes ne "yes") { 
    print "Parsing JSON failed\n"; 
} 
+0

どのようにデコードされたJSONが異なる/間違っていますか? –

答えて

1

デコードJSONが、この場合のPerlのハッシュリファレンスに変換されているので、あなたがそのようにアクセスします。

my $result = $decoded_json->{result}; 
print "$result->{first_name}\n"; 

出力:

[MAGA] 
+0

ありがとうございました! 'result' => { 'id' => 0000、 'username' => 'MAGA_bot'、 'first_name' => '[MAGA]' }この出力をすべて取得するにはどうすればよいですか? ? –

+0

'$ result - > {id}; $ result - > {username}; ' – stevieb

0

複雑なデータ構造の一部だけを表示したい場合は、データ構造のその部分を印刷します。

print Dumper $decoded_json->{result}; 
関連する問題