JSON:在创建带有 pretty-print 的文件时死于解码

标签 json perl pretty-print

当我使用 pretty-print 版本时,为什么会出现此错误?

'"' expected, at character offset 2 (before "(end of string)") at ./perl.pl line 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;

最佳答案

因为当您读回文件时,您使用的是 readline,并且只读取文件的第一行。当 pretty 关闭时,整个输出都在一行上。当漂亮打开时,JSON 分布在多行中,因此您将无效的截断 JSON 传递给 decode_json

使用local $/= undef;slurp 读取全部内容或者你想要的任何其他东西。

关于JSON:在创建带有 pretty-print 的文件时死于解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8403634/

相关文章:

json - 使用HCatalog JSON SerDe时出现 “Can not create a Path from an empty string”错误

perl - 算法效率提升

perl - Perl 的哪些特性使它成为一种函数式编程语言?

java - 使用 JSON Parsing with volley 更新 ListView 的最佳方法

python - Discord 金钱机器人将用户 ID 保存在 json 文件中。当 Not 重新启动时,它会为每个人创建一个新的(但相同的)ID

javascript - 使用 AJAX 向服务器提交搜索条件的最佳方式?

perl - SQLite可以输出压缩整数吗?

jquery - css 旋转和对齐

haskell - Haskell 中 pretty-print 表达式结构?

git - 如何处理 git 存储库中广泛的代码格式更改