2016-04-27 53 views
0

我得到一個錯誤執行以下代碼的錯誤:decode_json錯誤越來越因爲編碼問題

use JSON; 
use Encode qw(encode decode encode_utf8 decode_utf8); 
my $arr_features_json = '[{"family":"1","id":107000,"unit":"","parent_id":"0","cast":"2","search_values_range":"1,2,3,4,5,6,7,8,9,10,11,12","category_id":"29","type":"2","position":"3","name":"Número de habitaciones","code":"numberofrooms","locales":"4","flags":"1"}]'; 
$arr_features_json = decode_json($arr_features_json); 

以下是我的錯誤:在JSON

畸形的UTF-8字符字符串,字符offset 169(前 「\ X {FFFD}德habitaci ...」)在test.pl線13

decode_json被髮出,因爲的誤差json中的字符,所以我想將此字符轉換爲\u00fa。我怎樣才能做到這一點?

回答

1

錯誤提示您嘗試處理的字符串不是UTF-8或錯誤的UTF-8字符串。因此,在將其解碼爲json之前,需要使用encode_utf8將其轉換爲UTF-8字符串。

use JSON; 
use Data::Dumper; 
use Encode qw(encode decode encode_utf8 decode_utf8); 

my $arr_features_json = '[{"family":"1","id":107000,"unit":"","parent_id":"0","cast":"2","search_values_range":"1,2,3,4,5,6,7,8,9,10,11,12","category_id":"29","type":"2","position":"3","name":"Número de habitaciones","code":"numberofrooms","locales":"4","flags":"1"}]'; 
my $arr_features = decode_json(encode_utf8($arr_features_json)); 

print Dumper($arr_features); 

也許你應該檢查這個article知道UTF-8字符串和character strings之間的差異。

+2

這是倒退。 'decode_json'需要一個UTF-8字符串(字節),但輸入包含一個「寬字符」。 'encode_utf8'將一個非UTF-8編碼的字符串轉換爲一個字符串。 (嗯,它也可以將一個已經被UTF-8編碼的字符串轉換成雙重編碼的字符串) – mob

+1

代碼是正確的,但是兩個解釋句子都是倒退的。 – ikegami

+0

謝謝@ikegami糾正。我之前沒有注意到它。 –

2

decode_json預計UTF-8,但您擁有的字符串不是使用UTF-8編碼的。 decode該字符串如果它尚未,則使用from_json而不是decode_json

#!/usr/bin/perl 

use strict; 
use warnings; 
use feature qw(say); 

use utf8;        # Perl code is encoded using UTF-8. 
use open ':std', ':encoding(UTF-8)'; # Terminal provides/expects UTF-8. 

use JSON qw(from_json); 

my $features_json = ' 
    [ 
    { 
     "family": "1", 
     "id": 107000, 
     "unit": "", 
     "parent_id": "0", 
     "cast": "2", 
     "search_values_range": "1,2,3,4,5,6,7,8,9,10,11,12", 
     "category_id": "29", 
     "type": "2", 
     "position": "3", 
     "name": "Número de habitaciones", 
     "code": "numberofrooms", 
     "locales": "4", 
     "flags": "1" 
    } 
    ] 
'; 

my $features = from_json($features_json); 

say $features->[0]{name};