[PERL] JSON物件的使用

URL Link //n.sfs.tw/16442

2024-08-24 00:22:00 By 張○○

PERL要使用json,可以使用 JSON這個模組。

use JSON;

 

一、安裝[1]

yum install cpan

cpan install JSON

二、將 hash 轉成json、json_encode

1. 使用 JSON 模組

use JSON;

my %data = (
    name => "Alice",
    age  => 25,
    skills => ["Perl", "Python", "C++"]
);

# 建立 JSON 物件
my $json = JSON->new->utf8->pretty;

# 轉成 JSON 字串
my $json_text = $json->encode(\%data);

print $json_text;

結果

{
   "age" : 25,
   "name" : "Alice",
   "skills" : [
      "Perl",
      "Python",
      "C++"
   ]
}

2. 使用 JSON::PP 這個模組

use JSON::PP;

my %hash = (
    fruit => "apple",
    color => "red"
);

my $json = JSON::PP->new->utf8->pretty->encode(\%hash);

print $json;

3. 使用 json_encode

use JSON;
print encode_json(\%hash);

 

三、將 json 轉成物件

my $decoded = decode_json($json_text);
print $decoded->{name};

 

四、傾印hash

foreach my $key (keys %hash) {
    print "$key => $hash{$key}\n";
}

或用dumper

use Data::Dumper;

my %hash = (
    name => "Alice",
    age  => 25,
    hobbies => ["music", "reading"],
);

print Dumper(\%hash);

結果

$VAR1 = {
      'hobbies' => [
           'music',
           'reading'
      ],
      'age' => 25,
      'name' => 'Alice'
   };

 

 

參考資料

[1] https://stackoverflow.com/questions/12027327/how-to-install-json-pm-perl-module-on-osx

[2] https://stackoverflow.com/questions/48304117/perl-iterate-through-a-json-string-get-key-value-object-in-one-variable