How to access data in JSON by key

Viewed 117

I need to open file with JSON and read 2 variables, and assign values to vars in my program. How to do it?

sub Config {
my $filename = 'perl_config.txt';
my $json_text = do {
    open(my $json_fh, "<:encoding(UTF-8)", $filename)
        or die("Can't open \$filename\": $!\n");
    local $/;
    <$json_fh>
};
my $json = JSON->new;
my $data = $json->decode($json_text);



for my $key (sort keys %{$data}) {
    print "${key}:"; #how to acces to data by these keys?
    print "\n";
}

My json file looks:

{
"local_host": "localhost",
"local_port": "6000"
}
2 Answers

$data is a hash ref. You can access each value from its key just like you would do with a regular hash, so:

for my $key (sort keys %{$data}) {
    print "$key = ", $data->{$key}, "\n"; 
}

This should be enough to get you there:

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

use JSON;

my $json = do { local $/; <DATA> };

my $data = JSON->new->decode($json);

say "Host is: $data->{local_host}";
say "Port is: $data->{local_port}";

__DATA__
{
"local_host": "localhost",
"local_port": "6000"
}
Related