2016-04-27 10 views
0

エラーを取得:JSONでdecode_jsonエラー私は、次のコードを実行し、エラーを取得していますので、エンコードの問題の

不正なUTF-8文字:

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); 

次は私が取得エラーです文字列、文字でtest.plラインで( "\のX {FFFD}デhabitaci ..." 前)169オフセット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); 

おそらくあなたはUTF-8文字列とcharacter stringsの違いを知るために、このarticleをチェックする必要があります。

+2

これは後方です。 'decode_json'はUTF-8文字列(オクテット)を期待していますが、入力には「ワイド文字」が含まれています。 'encode_utf8'は、UTF-8でない文字列を文字列に変換します。 (まあ、すでにUTF-8でエンコードされた文字列を二重にエンコードされた文字列に変換することもできます) – mob

+1

コードは正しいですが、説明の両方の文が後方にあります。 – ikegami

+0

ありがとう@ikegamiが修正されました。私は前にそれに気付かなかった。 –

2

decode_jsonはUTF-8を想定していますが、使用している文字列はUTF-8を使用してエンコードされていません。 decode文字列がまだない場合は、decode_jsonの代わりにfrom_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}; 
関連する問題