user3055744
user3055744

Reputation: 21

How to append an object into a JSON array in perl?

I tried to append the object into the json array but it ended up showing as a different format. I would be very grateful if anyone can show me the correct way.

Here is my code:

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; 


}

The result shows:

[{"Release":"11.0","Build":"135"}][{"Release":"12.0","Build":"120"}] ...

But the result I would like to get is:

[{"Release":"11.0","Build":"135"},{"Release":"12.0","Build":"120"}, ...]

Upvotes: 1

Views: 2212

Answers (1)

ikegami
ikegami

Reputation: 386706

To add to the array represented in the JSON file, you'll need to actually obtain that array first!

my $json = do { local $/; <> };
my $releases = decode_json($json);
push @$releases, \%hshReleasebuild;
print encode_json($releases);

(Dealing with file handles other than STDIN and STDOUT left to you.)

Upvotes: 2

Related Questions