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

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

[root@tts177:/tmp]$/opt/php/bin/php -r 'echo json_encode(Array("a"=>"测试"))." ";'
{"a":"u6d4bu8bd5"}
[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":"u6d4bu8bd5"}';   ##就是上面的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":"u6d4bu8bd5"}';
my $p = decode_json($str);

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

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

[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