简体   繁体   English

无法使用 Cpanel::JSON::XS 解码 UTF-8 编码的 json 文本

[英]Not able to decode UTF-8 encoded json text with Cpanel::JSON::XS

I am trying to decode an UTF-8 encoded json string with Cpanel::JSON::XS :我正在尝试使用Cpanel::JSON::XS解码 UTF-8 编码的 json 字符串:

use strict;
use warnings;
use open ':std', ':encoding(utf-8)';
use utf8;
use Cpanel::JSON::XS;
use Data::Dumper qw(Dumper);
my $str = '{ "title": "Outlining — How to outline" }';
my $hash = decode_json $str;
#my $hash = Cpanel::JSON::XS->new->utf8->decode_json( $str );
print Dumper($hash);

but this throws an exception at decode_json :但这会在decode_json处引发异常:

Wide character in subroutine entry

I also tried Cpanel::JSON::XS->new->utf8->decode_json( $str ) (see commented out line), but this gives another error:我还尝试Cpanel::JSON::XS->new->utf8->decode_json( $str ) (请参阅注释掉的行),但这会产生另一个错误:

malformed JSON string, neither tag, array, object, number, string or atom, at character offset 0 (before "(end of string)")

What am I missing here?我在这里错过了什么?

decode_json expects UTF-8, but you are providing decoded text (a string of Unicode Code Points). decode_json需要 UTF-8,但您提供的是解码文本(Unicode 代码点的字符串)。

Use利用

use utf8;
use Encode qw( encode_utf8 );

my $json_utf8 = encode_utf8( '{ "title": "Outlining — How to outline" }' );

my $data = decode_json( $json_utf8 );

or或者

use utf8;

my $json_utf8 = do { no utf8; '{ "title": "Outlining — How to outline" }' };

my $data = decode_json( $json_utf8 );

or或者

use utf8;

my $json_ucp = '{ "title": "Outlining — How to outline" }';

my $data = Cpanel::JSON::XS->new->decode( $json_ucp );    # Implied: ->utf8(0)

(The middle one seems hackish to me. The first one might be used if you get data from multiple source, and the others provide it encoded.) (中间一个对我来说似乎很老套。如果您从多个来源获取数据,则可能会使用第一个,而其他人则提供编码。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM