珠海市中国灵车网

perl处理json的序列化和反序列化

2026-03-26 13:02:02 浏览次数:0
详细信息

JSON模块。以下是详细的使用方法:

1. 安装JSON模块

cpan install JSON
# 或
cpanm JSON

2. 基本使用方法

use JSON;

# 创建JSON对象
my $json = JSON->new;

# 设置选项(可选)
$json = JSON->new->utf8;            # 启用UTF-8编码
$json = JSON->new->pretty;          # 美化输出
$json = JSON->new->allow_nonref;    # 允许非引用值
$json = JSON->new->canonical;       # 按键名排序
$json = JSON->new->convert_blessed; # 允许序列化对象

3. JSON序列化(编码)

use JSON;

my $json = JSON->new->utf8->pretty;

# 哈希引用转JSON
my $hash_ref = {
    name => "张三",
    age  => 30,
    skills => ["Perl", "Python", "JavaScript"]
};

my $json_string = $json->encode($hash_ref);
print $json_string;

4. JSON反序列化(解码)

use JSON;

my $json = JSON->new->utf8;

# JSON字符串转Perl数据结构
my $json_str = '{"name":"李四","age":25,"city":"北京"}';
my $perl_data = $json->decode($json_str);

print "姓名: " . $perl_data->{name} . "\n";
print "年龄: " . $perl_data->{age} . "\n";
print "城市: " . $perl_data->{city} . "\n";

5. 常用选项设置

use JSON;

my $json = JSON->new;

# 常用选项组合
$json->utf8(1);           # UTF-8编码
$json->pretty(1);         # 美化输出(缩进)
$json->indent(1);         # 缩进
$json->space_before(1);   # 键前加空格
$json->space_after(1);    # 键后加空格
$json->relaxed(1);        # 更宽松的解析
$json->allow_nonref(1);   # 允许非引用
$json->convert_blessed(1);# 转换blessed对象

6. 处理复杂数据结构

use JSON;

my $data = {
    users => [
        {
            id => 1,
            name => "王五",
            email => "wangwu@example.com"
        },
        {
            id => 2,
            name => "赵六",
            email => "zhaoliu@example.com"
        }
    ],
    company => {
        name => "ABC公司",
        location => "上海"
    }
};

my $json = JSON->new->utf8->pretty;
my $json_output = $json->encode($data);
print $json_output;

7. 错误处理

use JSON;
use Try::Tiny;

my $json_str = '{"name": "test", "age": }'; # 无效JSON

try {
    my $json = JSON->new;
    my $data = $json->decode($json_str);
    print "解析成功\n";
} catch {
    my $error = $_;
    print "JSON解析错误: $error\n";
};

8. 使用JSON::XS(更快)

如果需要更高性能,可以使用JSON::XS:

use JSON::XS;

my $json = JSON::XS->new->utf8;

# 编码
my $json_str = $json->encode({foo => 'bar', baz => [1, 2, 3]});

# 解码
my $data = $json->decode($json_str);

9. 完整示例

#!/usr/bin/perl
use strict;
use warnings;
use JSON;

# 创建JSON处理器
my $json = JSON->new->utf8->pretty->allow_nonref;

# 示例数据结构
my $person = {
    name => "张三",
    age => 28,
    married => JSON::false,  # JSON布尔值
    hobbies => ["阅读", "游泳", "编程"],
    address => {
        city => "北京",
        street => "朝阳路123号"
    }
};

# 序列化为JSON
print "=== JSON输出 ===\n";
my $json_text = $json->encode($person);
print $json_text . "\n";

# 反序列化回Perl
print "\n=== 解析JSON ===\n";
my $decoded = $json->decode($json_text);
print "姓名: " . $decoded->{name} . "\n";
print "年龄: " . $decoded->{age} . "\n";
print "城市: " . $decoded->{address}{city} . "\n";

注意事项

编码问题:确保正确处理UTF-8编码 循环引用:JSON模块不能处理循环引用的数据结构 对象序列化:默认不能序列化blessed对象,需要设置convert_blessed选项 性能考虑:对于大量数据处理,建议使用JSON::XS

这些是Perl中处理JSON的基本方法,可以根据实际需求调整配置选项。

相关推荐