json 模块

JSON:

JSON-JSON (JavaScript 对象标记)  编码/解码

简介:

 use JSON; # imports encode_json, decode_json, to_json and from_json.


##简单和快速接口(期望/生产 UTF-8)

 $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;

 $perl_hash_or_arrayref  = decode_json $utf8_encoded_json_text;


面对对象接口:

 $json = JSON->new->allow_nonref;
 
 $json_text   = $json->encode( $perl_scalar );
 $perl_scalar = $json->decode( $json_text );
 
 $pretty_printed = $json->pretty->encode( $perl_scalar ); # pretty-printing





生产json 格式:

[root@dr-mysql01 ~]# cat a3.pl 
use JSON qw/encode_json decode_json/;    
my $data = [    
    {  
        'name' => '灰灰',  
        'age' => 19  
    },  
    {  
        'name' => '丽丽',  
        'age' => 25  
    }  
];


my $json_out = encode_json($data);    
print $json_out;  
print "\n";  
You have mail in /var/spool/mail/root
[root@dr-mysql01 ~]# perl a3.pl 
[{"age":19,"name":"灰灰"},{"name":"丽丽","age":25}]


[root@dr-mysql01 ~]# cat a3.pl 
use JSON qw/encode_json decode_json/;    
use Encode;

my $data = [    
    {  
        'name' => '灰灰',  
        'age' => 19  
    },  
    {  
        'name' => '丽丽',  
        'age' => 25  
    }  
];

 $json = JSON->new->allow_nonref;
 
 $json_out   = $json->encode( $data );

print $json_out;  
print "\n";  
[root@dr-mysql01 ~]# perl a3.pl 
[{"age":19,"name":"灰灰"},{"name":"丽丽","age":25}]






encode_json:

$json_text = encode_json $perl_scalar


转换给定的perl 数据结构为一个UTF-8 encoded,binary 字符串:

$json_text = JSON->new->utf8->encode($perl_scalar)


decode_json

$perl_scalar = decode_json $json_text


与encode_json 相反,期望一个UTF-8(2进制的)字符串和尝试 解析一个UTF-8 encoded JSON 文本,

返回一个结果引用










posted @ 2016-05-20 10:50  czcb  阅读(197)  评论(0编辑  收藏  举报