Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access data in JSON by key

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"
}

1 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"; 
}
like image 188
GMB Avatar answered Oct 30 '25 19:10

GMB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!