在Perl中,如何只打印通过json提取的值?

时间:2017-07-26 05:58:54

标签: json perl

我有一个包含内容的json文件。我正在打开json extract_json。我想访问属性“d”的值

def lambda_handler(event, context):
    client = boto3.client('ec2')
    s3_client = boto3.client('s3')
    # Download private key file from secure S3 bucket
    s3_client.download_file('test','test.pem', '/tmp/test.pem')
    k = paramiko.RSAKey.from_private_key_file("/tmp/test.pem")
    c = paramiko.SSHClient()
    c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    bastion_host = "xxx.com"
    print ("Connecting to " + bastion_host)
    c.connect(hostname=bastion_host, username="yyy", key_filename="/tmp/test.pem")
    print ("Connected to " + bastion_host)
    commands = [

        "sh /home/ec2-user/TestDeploy.sh"
    ]
    for command in commands:
        print ("Executing {}".format(command))
        stdin, stdout, stderr = c.exec_command(command)
        print (stdout.read())
        print (stderr.read())
return 'Hello from Lambda'

变量d的内容是['31','45']。 我需要将分配给“var”的值设为['31','45']。

请帮助我获得所需的输出。

2 个答案:

答案 0 :(得分:0)

尝试以下

use warnings;
use strict;
use JSON::XS;
my $targetfile = extract_json('file.json');
my $object = JSON::XS->new->utf8->decode($targetfile);

my $flat_hash = 
{
    'var'=> $object->{'a'}{'b'}{'c'}{'d'}
};


sub extract_json{
    my $file = shift;
    local $/;
    open my $fh, "<", "$file";
    my $json = <$fh>;
    return $json;
}

foreach my $key (keys %{$flat_hash}) #Dereferencing hash ref
{

    foreach (@{$$flat_hash{$key}})  #Iterating loop for array ref
    {
        print "$key => $_\n";
    }

}

答案 1 :(得分:0)

试试这段代码:

use strict;
use warnings;
use JSON;
use Data::Dumper;

sub extract_json{
        my $file =shift;
        open(my $fh, "<:encoding(UTF-8)" , $file) || die "couldn't open $file";
        local $/;
        my $json=<$fh>;
return $json;
}

my $targetfile = extract_json('example.json');
my $object = JSON->new;
my $decoded= $object->decode($targetfile);

my $flat_hash ={
               'var' => $decoded->{a}{b}{c}->@{d},
     };
 print Dumper $flat_hash;