当前位置: 代码网 > it编程>网页制作>Perl > perl处理json的序列化和反序列化

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

2024年05月15日 Perl 我要评论
perl可以使用json模块很方便的处理json的序列化和反序列化。先来一段简单的例子:#! /usr/bin/perluse v5.14;use json;use io::file;my $info

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 });

脚本执行后的输出结果:

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这些特殊值,可以如下使用,在之前的那个脚本中我们继续添加举例:

#! /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内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com