I have a json file, which I am processing using perl JSON module.
Once I process it, I want to insert some content to in it.
Here is my input json file:
{
"sequence" : [
{
"type" : "event",
"attribute" : {
"contentText" : "Test Content",
"contentNumber" : "11"
}
}
],
"current" : 0,
"next" : 1
}
And below is my script:
#!/usr/bin/perl
use strict;
use warnings;
use JSON;
use Data::Dumper;
my $needed = 2;
my $filename = "test_file.json";
my $json_text = do {
open(my $json_fh, "<:encoding(UTF-8)", $filename)
or die("Can't open \$filename\": $!\n");
local $/;
<$json_fh>
};
my $json = JSON->new;
my $data = $json->decode($json_text);
my $aref = $data->{sequence};
print Dumper($aref);
my $number;
for my $element (@$aref) {
$number = $element->{attribute}->{contentNumber}."\n";
}
print "Number:$number\n";
my $total = $number + $needed;
foreach my $each_number ($number+1..$total){
print $each_number."\n";
}
print Dumper $data;
So what I needed over here is fetch contentNumber from given json file and increment value by 1 till $needed is mentioned and form a new json file.
And finally it should form JSON file which should have content like below:
Where whatever $needed variable value is mentioned that many times the json should form the data including the initial data.
{
"sequence" : [
{
"type" : "event",
"attribute" : {
"contentText" : "Test Content",
"contentNumber" : "11"
}
},
{
"type" : "event",
"attribute" : {
"contentText" : "Test Content",
"contentNumber" : "12"
}
},
{
"type" : "event",
"attribute" : {
"contentText" : "Test Content",
"contentNumber" : "13"
}
}
],
"current" : 0,
"next" : 1
}
I was thinking to push the data in foreach loop. But no clue how we can put it in data object which should give me an output with json format.