perl處理json的序列化和反序列化
perl可以使用JSON模塊很方便的處理json的序列化和反序列化。先來一段簡單的例子:
#! /usr/bin/perl use v5.14; use JSON; use IO::File; my $info = { id => 1024, desc => 'hello world', arry => [1, 2, 3, 4, 5], obj => { char => [ 'A', 'B', 'C' ] } }; say to_json($info, { pretty => 1 });
腳本執(zhí)行后的輸出結果:
to_json 就是序列化,把hash對象序列化為json字符串,如果有需要,可以直接把這個字符串寫入文件。函數調用中有一個 pretty => 1 的使用,默認不傳入這個參數或者 pretty => 0, 結果如下:
{"arry":[1,2,3,4,5],"desc":"hello world","id":1024,"obj":{"char":["A","B","C"]}}
json中如果要使用 true、false、null這些特殊值,可以如下使用,在之前的那個腳本中我們繼續(xù)添加舉例:
#! /usr/bin/perl use v5.14; use JSON; use IO::File; my $info = { id => 1024, desc => 'hello world', arry => [1, 2, 3, 4, 5], obj => { char => [ 'A', 'B', 'C' ] }, other_1 => { test_true => \1, test_false => \0, test_null => undef }, other_2 => { test_true => JSON::true, test_false => JSON::false, test_null => JSON::null } }; say to_json($info, { pretty => 1 });
輸出結果如下:
{
"other_2" : {
"test_true" : true,
"test_null" : null,
"test_false" : false
},
"obj" : {
"char" : [
"A",
"B",
"C"
]
},
"arry" : [
1,
2,
3,
4,
5
],
"id" : 1024,
"other_1" : {
"test_false" : false,
"test_null" : null,
"test_true" : true
},
"desc" : "hello world"
}
在腳本中可以清楚的看到兩種表示方法:
了解了JSON模塊的序列化,下面來看反序列化的處理,為了說明簡潔,這里直接把上面腳本的輸出結果加在腳本中,使用perl的DATA句柄讀取數據,腳本如下:
#! /usr/bin/perl use v5.14; use JSON; use IO::File; # 讀取json字符串數據 my $json_str = join('', <DATA>); # 反序列化操作 my $json = from_json($json_str); say $json->{desc}; say '-' x 60; say $json->{other_1}{test_true}; say $json->{other_1}{test_false}; unless (defined $json->{other_1}{test_null}) { say '---------null'; } say '-' x 60; say for @{ $json->{arry} }; __DATA__ { "id" : 1024, "desc" : "hello world", "other_1" : { "test_null" : null, "test_false" : false, "test_true" : true }, "obj" : { "char" : [ "A", "B", "C" ] }, "other_2" : { "test_false" : false, "test_null" : null, "test_true" : true }, "arry" : [ 1, 2, 3, 4, 5 ] }
腳本讀取json字符串數據后使用from_json反序列化得到一個hash引用,然后打印出部分字段的值,結果如下:
hello world
------------------------------------------------------------
1
0
---------null
------------------------------------------------------------
1
2
3
4
5
可以看到,輸出值是正確的。其中true輸出的是1,false輸出的是0。
到此這篇關于perl處理json的序列化和反序列化的文章就介紹到這了,更多相關perl處理json內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Perl實現刪除Windows下的圖片緩存縮略圖Thumbs.db
這篇文章主要介紹了Perl實現刪除Windows下的圖片緩存縮略圖Thumbs.db,本文實現了批量刪除Thumbs.db文件,需要的朋友可以參考下2014-12-12