我在use JSON::XS qw(encode_json);
中遇到了encode_json函数的问题。我们有一个基于Web的项目,以Perl,JavaScript,jQuery和MySQL作为后端。
在应用程序的特定屏幕中,用户名称失真。
问题是用户名是西班牙语并且有重音字符。 我们保存数据库的表是旧表,并且有charset latin 1,但是当我获取数据时,我正在使用强制转换并将其转换为UTF-8格式。
select CONVERT(CAST(CONVERT(u.last_name USING latin1) AS BINARY) USING utf8) AS last_name from user where user_id = 'XXX'
在我存储数据库结果的结构中,数据看起来很好。
{ last_name => Cvas García}
将此结构传递给呈现页面的javascript函数
$data_json = encode_json( $data )
当我打印$data_json
时,重音字符再次失真。
"user_permissions":[{"last_name":"Cvas GarcÃa"}]},
任何人都可以帮我解决这个问题,无论是使用Mysql还是perl或javascript代码?
答案 0 :(得分:2)
桌子的字符集无关紧要。 MySQL将自动从表的编码转换为连接的编码。然后,您必须在Perl端对其进行解码,无论是显式还是将mysql_enable_utf8 => 1
传递给connect
。我推荐后者。
use utf8; # Source code encoded using UTF-8.
use open ':std', ':encoding(UTF-8)'; # Terminal expects/provides UTF-8.
use DBI qw( );
use JSON::XS qw( encode_json );
my $user_id = "...";
my $dsn = "...";
my $user = "...";
my $password = "...";
my $dbh = DBI->connect("dbi:mysql:".$dsn, $user, $password, {
PrintError => 0,
RaiseError => 1,
mysql_enable_utf8 => 1, # Switch to UTF-8 for communication and decode.
});
my $name = $dbh->selectrow_array("
SELECT `last_name`
FROM `user`
WHERE `user_id` = ?
", undef, $user_id);
# Encoding being performed by "use open".
print(sprintf("%vX", $name), "\n"); # 47.61.72.63.ED.61
print($name, "\n"); # García
# Encoding being performed by "use open".
my $json = JSON::XS->new->encode([$name]);
print(sprintf("%vX", $json), "\n"); # 5B.22.47.61.72.63.ED.61.22.5D
print($json, "\n"); # ["García"]
binmode(STDOUT); # Override "use open".
my $json_utf8 = JSON::XS->new->utf8->encode([$name]); # aka encode_json([$name])
print(sprintf("%vX", $json_utf8), "\n"); # 5B.22.47.61.72.63.C3.AD.61.22.5D
print($json_utf8, "\n"); # ["García"]
答案 1 :(得分:-1)
试试这个
use JSON;
use utf8;
use Data::Printer;
utf8::encode($data) unless (utf8::is_utf8($data));
p encode_json($data);