我试图将对象附加到json数组中,但最终显示为不同的格式。如果有人能告诉我正确的方法,我将非常感激。
这是我的代码:
sub create_release_text_file
{
my $result_path = shift;
my %hshReleasebuild ;
my @Releasebuild ;
my $json = JSON->new->allow_nonref;
my $release_path = File::Spec->catfile($result_path, "release.txt");
$hshReleasebuild{"Build"} = $ARG_BUILD;
$hshReleasebuild{"Release"} = $ARG_RELEASE;
push(@Releasebuild,\%hshReleasebuild);
my $json_releasebuild = $json->encode(\@Releasebuild );
open RELEASE_FILE, ">>", $release_path or die $!;
print RELEASE_FILE $json_releasebuild;
close RELEASE_FILE;
}
结果显示:
[{"Release":"11.0","Build":"135"}][{"Release":"12.0","Build":"120"}] ...
但我想得到的结果是:
[{"Release":"11.0","Build":"135"},{"Release":"12.0","Build":"120"}, ...]
答案 0 :(得分:2)
要添加到JSON文件中表示的数组,您需要首先实际获取该数组!
my $json = do { local $/; <> };
my $releases = decode_json($json);
push @$releases, \%hshReleasebuild;
print encode_json($releases);
(处理除STDIN和STDOUT之外的文件句柄。)