Perl的JSON :: XS无法正确编码UTF8吗? [英] Perl's JSON::XS not encoding UTF8 correctly?
问题描述
这个简单的代码段显示了我在Perl中使用JSON :: XS编码遇到的问题:
This simple code segment shows an issue I am having with JSON::XS encoding in Perl:
#!/usr/bin/perl
use strict;
use warnings;
use JSON::XS;
use utf8;
binmode STDOUT, ":encoding(utf8)";
my (%data);
$data{code} = "Gewürztraminer";
print "data{code} = " . $data{code} . "\n";
my $json_text = encode_json \%data;
print $json_text . "\n";
产生的输出是:
johnnyb@boogie:~/Projects/repos > ./jsontest.pl
data{code} = Gewürztraminer
{"code":"Gewürztraminer"}
现在,如果我注释掉上面的binmode行,我将得到:
Now if I comment out the binmode line above I get:
johnnyb@boogie:~/Projects/repos > ./jsontest.pl
data{code} = Gew�rztraminer
{"code":"Gewürztraminer"}
这是怎么回事?请注意,我试图在无法使用binmode的perl CGI脚本中解决此问题,但我总是得到JSON流中返回的上述¼"字符.我该如何调试呢?我想念什么?
What is happening here? Note that I am trying to fix this behavior in a perl CGI script in which binmode can not be used but I always get the "ü" characters as above returned in the JSON stream. How do I debug this? What am I missing?
推荐答案
encode_json
(JSON::XS->new->utf8->encode
的缩写)使用UTF-8进行编码,然后通过将其打印到已添加到的STDOUT来对其进行重新编码.添加了一个编码层.实际上,您正在执行encode_utf8(encode_utf8($uncoded_json))
.
encode_json
(short for JSON::XS->new->utf8->encode
) encodes using UTF-8, then you are re-encoding it by printing it to STDOUT to which you've added an encoding layer. Effectively, you are doing encode_utf8(encode_utf8($uncoded_json))
.
use open ':std', ':encoding(utf8)'; # Defaults
binmode STDOUT; # Override defaults
print encode_json(\%data);
解决方案2
use open ':std', ':encoding(utf8)'; # Defaults
print JSON::XS->new->encode(\%data); # Or to_json from JSON.pm
解决方案3
以下内容可通过对非ASCII使用\u
转义符在STDOUT上进行任何编码:
Solution 3
The following works with any encoding on STDOUT by using \u
escapes for non-ASCII:
print JSON::XS->new->ascii->encode(\%data);
在评论中,您提到它实际上是CGI脚本.
In the comments, you mention it's actually a CGI script.
#!/usr/bin/perl
use strict;
use warnings;
use utf8; # Encoding of source code.
use open ':encoding(UTF-8)'; # Default encoding of file handles.
BEGIN {
binmode STDIN; # Usually does nothing on non-Windows.
binmode STDOUT; # Usually does nothing on non-Windows.
binmode STDERR, ':encoding(UTF-8)'; # For text sent to the log file.
}
use CGI qw( -utf8 );
use JSON::XS qw( );
{
my $cgi = CGI->new();
my $data = { code => "Gewürztraminer" };
print $cgi->header('application/json');
print encode_json($data);
}
这篇关于Perl的JSON :: XS无法正确编码UTF8吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!