📅  最后修改于: 2020-11-13 05:10:25             🧑  作者: Mango
本章介绍如何使用Perl编程语言编码和解码JSON对象。让我们从准备环境开始,开始使用Perl for JSON进行编程。
在开始使用Perl编码和解码JSON之前,您需要安装JSON模块,该模块可以从CPAN获得。下载JSON-2.53.tar.gz或任何其他最新版本后,请按照以下步骤操作-
$tar xvfz JSON-2.53.tar.gz
$cd JSON-2.53
$perl Makefile.PL
$make
$make install
Function | Libraries |
---|---|
encode_json | Converts the given Perl data structure to a UTF-8 encoded, binary string. |
decode_json | Decodes a JSON string. |
to_json | Converts the given Perl data structure to a json string. |
from_json | Expects a json string and tries to parse it, returning the resulting reference. |
convert_blessed | Use this function with true value so that Perl can use TO_JSON method on the object’s class to convert an object into JSON. |
Perl encode_json()函数将给定的Perl数据结构转换为UTF-8编码的二进制字符串。
$json_text = encode_json ($perl_scalar );
or
$json_text = JSON->new->utf8->encode($perl_scalar);
以下示例显示了使用Perl的JSON下的数组-
#!/usr/bin/perl
use JSON;
my %rec_hash = ('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
my $json = encode_json \%rec_hash;
print "$json\n";
在执行时,这将产生以下结果-
{"e":5,"c":3,"a":1,"b":2,"d":4}
以下示例显示了如何将Perl对象转换为JSON-
#!/usr/bin/perl
package Emp;
sub new {
my $class = shift;
my $self = {
name => shift,
hobbies => shift,
birthdate => shift,
};
bless $self, $class;
return $self;
}
sub TO_JSON { return { %{ shift() } }; }
package main;
use JSON;
my $JSON = JSON->new->utf8;
$JSON->convert_blessed(1);
$e = new Emp( "sachin", "sports", "8/5/1974 12:20:03 pm");
$json = $JSON->encode($e);
print "$json\n";
执行时,将产生以下结果-
{"birthdate":"8/5/1974 12:20:03 pm","name":"sachin","hobbies":"sports"}
Perl encode_json()函数用于在Perl中解码JSON。此函数将从json解码的值返回到适当的Perl类型。
$perl_scalar = decode_json $json_text
or
$perl_scalar = JSON->new->utf8->decode($json_text)
以下示例显示了如何使用Perl解码JSON对象。如果您的计算机上尚未安装Data :: Dumper模块,则需要在此处安装。
#!/usr/bin/perl
use JSON;
use Data::Dumper;
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$text = decode_json($json);
print Dumper($text);
在执行时,将产生以下结果-
$VAR1 = {
'e' => 5,
'c' => 3,
'a' => 1,
'b' => 2,
'd' => 4
};