[精讚] [會員登入]
600

[PERL] JSON物件的使用

“
PERL要處理JSON,可以使用perl提供的模組,一些技巧整理。
„

分享此文連結 //n.sfs.tw/16442

分享連結 [PERL] JSON物件的使用@新精讚
(文章歡迎轉載,務必尊重版權註明連結來源)
2025-11-05 00:58:40 最後編修
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

END

你可能感興趣的文章

[PERL] split 寫法 Perl 將字串分開可以用 split 這個函數,此函數可以用Regex作分隔判斷

[PERL] 08-陣列 #2 --操作 更多perl陣列的操作,如拆開、黏合、取出、加入等等

Apache Worker MPM =worker 調整參數 Apache目前一共有三種穩定的MPM(Multi-Processing Module,多進程處理模式 簡稱: MPM)

[PERL] 07-陣列 #1 -- 基本 perl的陣列

[PERL] 中文字字串拆解,把中文字串逐字拆開 中文字字串拆解是門學問

[PERL] 04-基本比對 perl的正規表達示基本比對

隨機好文

[Windows7] 移除IE10及移除IE11 Windows7 不得已的情況要移除IE11或IE10怎麼做?

世紀帝國征服者新版本--被遺忘的帝國 世紀帝國征服者新版本--被遺忘的帝國 世紀二代的征服者是精典遊戲中的精典,aofe更好玩...

[PHP] 檢查檔案是否是圖檔 使用getimagesize函數檢查檔案是否是圖檔

[Wildfly10] 發佈war檔 deploy war file onto wildfly10

「許功蓋」的字以及源由 有玩過電腦一段時間的人,都聽過這個人(有一天我才發現7年級的竟然都不認識這個