我正在嘗試使用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)")
我在這里想念什么?
uj5u.com熱心網友回復:
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://www.uj5u.com/net/456229.html
