perl处理含有中文字符的json编码

例子:
1. 有php的 json函数生成的中文串

[root@tts177:/tmp]$/opt/php/bin/php -r 'echo json_encode(Array("a"=>"测试"))."\n";'
{"a":"\u6d4b\u8bd5"}
[root@tts177:/tmp]$

 

2. perl代码和执行结果如下:

[root@tts177:/tmp]$more uuu.pl
#!/usr/bin/perl
use warnings;
use Data::Dumper;
use JSON;
use Encode;
use URI::Escape;

my $str = '{"a":"\u6d4b\u8bd5"}';   ##就是上面的php字符串
my $p = decode_json($str);
print Dumper $p;
[root@tts177:/tmp]$
[root@tts177:/tmp]$./uuu.pl
$VAR1 = {
'a' => "\x{6d4b}\x{8bd5}"  ##怪了吧,要是用php自带的json_decode($str,true)函数,解析出来的就是正常中文。
};
[root@tts177:/tmp]$

 

3. 解决方法,参考:
http://bbs.chinaunix.net/thread-1340623-1-1.html     6楼的帖子

4. 如下代码是解决方法

[root@tts177:/tmp]$more uuu.pl
#!/usr/bin/perl
use warnings;
use Data::Dumper;
use JSON;
use Encode;
use URI::Escape;   ##正如帖子所说,不能用"use utf8"

my $str = '{"a":"\u6d4b\u8bd5"}';
my $p = decode_json($str);

my $s = $p->{'a'};
print $s,"\n";    ##第一个打印会打印出"Wide character in print at ./uuu.pl line 12." ,而且有时候还是乱码!

utf8::encode($s);   ##这里要非常注意,此函数返回值为0。如果写成  $s = utf::encode($s); 就错了!
print $s,"\n";

[root@tts177:/tmp]$
[root@tts177:/tmp]$./uuu.pl
Wide character in print at ./uuu.pl line 12.
测试
测试
[root@tts177:/tmp]$

 

 

[root@tts177:/tmp]$more uuu.pl
#!/usr/bin/perl
use warnings;
use Data::Dumper;
#use URI::Escape;
my $unicode = "\x{505c}\x{8f66}";
utf8::encode( $unicode );
print $unicode;

[root@tts177:/tmp]$
[root@tts177:/tmp]$./uuu.pl
停车[root@tts177:/tmp]$

 

转载于:https://www.cnblogs.com/voiphudong/p/3646920.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值