【问题标题】:Input is not UTF-8 encoded输入不是 UTF-8 编码的
【发布时间】:2019-01-08 04:43:44
【问题描述】:

我的数据库是 utf8 感知的:

                                   List of databases
   Name    |     Owner     | Encoding |  Collate   |   Ctype    |
-----------+---------------+----------+------------+------------+
 tucha     | tucha_cleaner | UTF8     | en_US.utf8 | en_US.utf8 | 

当我连接到它时,我设置了client_encoding:

my $hm_schema = App::Schema->connect( $dsn, $user, $pass, {
        AutoCommit => 1,
        RaiseError => 1,
        client_encoding => 'UTF8',
    }
);

返回值,据我所知,是UTF8:

DBG>$value
["Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"]

DBG>use Devel::Peek

DBG>Devel::Peek::Dump $value
SV = PVMG(0xfe41c20) at 0xfe079b0
  REFCNT = 1
  FLAGS = (POK,IsCOW,pPOK,UTF8)
  IV = 0
  NV = 0
  PV = 0xfe27550 "[\"\320\235\320\264\", \"\320\237\320\275\", \"\320\222\321\202\", \"\320\241\321\200\", \"\320\247\321\202\", \"\320\237\321\202\", \"\320\241\320\261\"]"\0 [UTF8 "["\x{41d}\x{434}", "\x{41f}\x{43d}", "\x{412}\x{442}", "\x{421}\x{440}", "\x{427}\x{442}", "\x{41f}\x{442}", "\x{421}\x{431}"]"]
  CUR = 56
  LEN = 58
  COW_REFCNT = 4
undef

但是当我尝试通过 decode_jsonMojo::JSON 解码该字符串时,我得到了错误:

DBG> decode_json $value
ERROR: Input is not UTF-8 encoded at ...

为什么会出现该错误以及如何解决?

【问题讨论】:

  • 那些在我看来不像编码字符:如果它们被编码,你将无法阅读它们!请改用from_json。如果您必须猜测输出的含义,请不要使用Devel::Peek:perl 用于表示字符串的内部编码无关紧要。
  • @Borodin:啊,我应该只在字节流上使用decode_json

标签: postgresql perl dbi mojolicious


【解决方案1】:

字符串的前 5 个字符如下(十六进制):

5B 22 41D 434 22

UTF-8 等字符编码是使用字节表示代码点的方法,其中两个字符不是字节,因此您的字符串不可能使用 UTF-8 进行 JSON 编码。

您似乎有一个已解码的字符串。已删除字符编码以生成一串 Unicode 代码点。如果这是你所拥有的,请替换

JSON::decode_json($json_utf8)
JSON::MaybeXS::decode_json($json_utf8)
JSON::PP::decode_json($json_utf8)
JSON::XS::decode_json($json_utf8)
Cpanel::JSON::XS::decode_json($json_utf8)

JSON->new->decode($json_ucp)    -or-    JSON::from_json($json_ucp)
JSON::MaybeXS->new->decode($json_ucp)
JSON::PP->new->decode($json_ucp)
JSON::XS->new->decode($json_ucp)
Cpanel::JSON::XS->new->decode($json_ucp)

顺便说一句,除非您想查看 Perl 内部结构,否则 Devel::Peek 并不是适合这项工作的工具。您应该改用 Data::Dumper 或类似的。

use Data::Dumper qw( Dumper );
# This is the same string as in the OP.
my $value = qq{["\x{41d}\x{434}", "\x{41f}\x{43d}", "\x{412}\x{442}", "\x{421}\x{440}", "\x{427}\x{442}", "\x{41f}\x{442}", "\x{421}\x{431}"]};
local $Data::Dumper::Useqq = 1;
print(Dumper($value));

输出:

$VAR1 = "[\"\x{41d}\x{434}\", \"\x{41f}\x{43d}\", \"\x{412}\x{442}\", \"\x{421}\x{440}\", \"\x{427}\x{442}\", \"\x{41f}\x{442}\", \"\x{421}\x{431}\"]";

【讨论】:

    猜你喜欢
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    相关资源
    最近更新 更多