如何通过key访问JSON中的数据

How to access data in JSON by key

我需要用 JSON 打开文件并读取 2 个变量,并在我的程序中为变量赋值。怎么做?

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

我的 json 文件看起来:

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

$data 是哈希引用。您可以像使用常规哈希一样从其键访问每个值,因此:

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

这应该足以让你到达那里:

#!/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"
}