user3394199
user3394199

Reputation: 3

How to push a new value into a JSON object

I have an empty JSON object

{}

I would like to know how, in Perl, I could push values into the object so it'd end up looking like this

{"Test": 1}

Upvotes: 0

Views: 1371

Answers (2)

Borodin
Borodin

Reputation: 126772

You should build your data as a Perl data structure, and convert it to JSON when it is complete

If you were starting with some significant JSON data then you would decode it first and then add to the resultant Perl data structure, but it is trivial to create an empty Perl hash to start with

Your code would look like this

use strict;
use warnings 'all';

use JSON;

my %data;

$data{Test} = 1;

my $convert = JSON->new->pretty;
print $convert->encode(\%data);

output

{
   "Test" : 1
}

Upvotes: 5

Anton Petrusevich
Anton Petrusevich

Reputation: 172

#!/usr/bin/perl
use strict;
use warnings;
use JSON;
my $obj = {};
$obj->{'Test'} = 1;
print encode_json ($obj) . "\n";

A little bit of google-fu returns tutorial sites like JSON in Perl

Upvotes: 1

Related Questions