F. Grela
F. Grela

Reputation: 61

Working with JSON in perl

I need to print all "time" values from below JSON in Perl. How do it?

#!/usr/bin/perl -w
use strict;
use JSON;
use Data::Dumper;
$a = q({"Response":"Success","Type":100,"Aggregated":true,"Data":[{"time":1521064980,"close":8130.26,"high":8153.57,"low":8121.42,"open":8152.29,"volumefrom":711.3,"volumeto":5815443.51},{"time":1521065160,"close":8161.97,"high":8167.7,"low":8130.51,"open":8130.51,"volumefrom":527.3699999999999,"volumeto":4348419.180000001}{"time":1521075780,"close":8129.27,"high":8129.71,"low":8126.7,"open":8127.4,"volumefrom":50.35,"volumeto":412670.56000000006}],"TimeTo":1521075900,"TimeFrom":1521064980,"FirstValueInArray":true,"ConversionType":{"type":"direct","conversionSymbol":""}});

$b = decode_json $a;

Upvotes: 0

Views: 216

Answers (1)

Shuwn Yuan Tee
Shuwn Yuan Tee

Reputation: 5748

You can try below code to print values of time in your json:

#!/usr/bin/perl -w
use strict;
use JSON;
use Data::Dumper;

my $json = q({"Response":"Success","Type":100,"Aggregated":true,"Data":[{"time":1521064980,"close":8130.26,"high":8153.57,"low":8121.42,"open":8152.29,"volumefrom":711.3,"volumeto":5815443.51},{"time":1521065160,"close":8161.97,"high":8167.7,"low":8130.51,"open":8130.51,"volumefrom":527.3699999999999,"volumeto":4348419.180000001},{"time":1521075780,"close":8129.27,"high":8129.71,"low":8126.7,"open":8127.4,"volumefrom":50.35,"volumeto":412670.56000000006}],"TimeTo":1521075900,"TimeFrom":1521064980,"FirstValueInArray":true,"ConversionType":{"type":"direct","conversionSymbol":""}});

my $ref = decode_json $json;

# access 'Data' in hashref $ref
my $data = $ref->{'Data'};

# loop through item in array ref $data
for my $item (@{$data}) {
    # print value of "time" with a newline
    print $item->{'time'} . "\n";
}

# print 'TimeTo' value
print "TimeTo: " . $ref->{'TimeTo'};

Upvotes: 3

Related Questions