【发布时间】:2015-09-19 03:37:31
【问题描述】:
这个简单的代码段显示了我在 Perl 中使用 JSON::XS 编码时遇到的问题:
#!/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 行,我会得到:
johnnyb@boogie:~/Projects/repos > ./jsontest.pl
data{code} = Gew�rztraminer
{"code":"Gewürztraminer"}
这里发生了什么?请注意,我试图在无法使用 binmode 的 perl CGI 脚本中修复此行为,但我总是得到 JSON 流中返回的上述“ü”字符。我该如何调试?我错过了什么?
【问题讨论】:
-
将最后一行替换为
print decode('UTF-8', $json_text, Encode::FB_CROAK) . "\n";