2011-12-06 3 views
1

かなりのプリント版を使用すると、なぜこのエラーが発生しますか?JSON:きれいなプリントで作成したファイルをデコードするときに死ぬ

は./perl.plライン29

#!/usr/bin/env perl 
use warnings; 
use 5.014; 
use utf8; 
binmode STDOUT, ':encoding(utf-8)'; 
use Data::Dumper; 
use JSON; 

my $json = JSON->new->utf8; 
my $hashref = { 
    'muster, hanß' => { 
     'hello' => { 
      year => 2000, 
      color => 'green' 
     } 
    } 
}; 

my $utf8_encoded_json_text = $json->pretty->encode($hashref); # leads to a die 
#my $utf8_encoded_json_text = $json->encode($hashref); # works 

open my $fh, '>', 'testfile.json' or die $!; 
print $fh $utf8_encoded_json_text; 
close $fh; 

open $fh, '<', 'testfile.json' or die $!; 
$utf8_encoded_json_text = readline $fh; 
close $fh; 
$hashref = decode_json($utf8_encoded_json_text); 
say Dumper $hashref; 

答えて

7

で '"'(文字列の(終了) "期待、文字の前に)2をオフセット" ので、あなたが戻ってファイルを読み込むときに、あなたがreadlineを使用していて、ファイルの最初の行だけを読み込んでいます。かなりオフの場合、出力全体が1行になります。きれいにするとJSONが複数の行にまたがって渡されます無効な切り捨てJSONをdecode_jsonに変更します。

local $/ = undef;またはslurpなどを使用してください。

関連する問題