我正在尝试用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);但这会在decode_json引发异常
Wide character in subroutine entry我也尝试了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)")我在这里错过了什么?
发布于 2022-04-05 21:50:09
decode_json期望UTF-8,但您正在提供解码文本(一串Unicode代码点)。
使用
use utf8;
use Encode qw( encode_utf8 );
my $json_utf8 = encode_utf8( '{ "title": "Outlining — How to outline" }' );
my $data = decode_json( $json_utf8 );或
use utf8;
my $json_utf8 = do { no utf8; '{ "title": "Outlining — How to outline" }' };
my $data = decode_json( $json_utf8 );或
use utf8;
my $json_ucp = '{ "title": "Outlining — How to outline" }';
my $data = Cpanel::JSON::XS->new->decode( $json_ucp ); # Implied: ->utf8(0))在我看来,中间的那个似乎很讨厌。如果您从多个源获取数据,而其他来源提供了编码数据,则可以使用第一个。)
https://stackoverflow.com/questions/71758645
复制相似问题