win5rx win5rx - 2 years ago 100
Perl Question

Adding a key value pair to an existing json object in perl

I want to add a key value pair to a JSON object. Following is the structure of Param{Data} variable for the below code.

$VAR1 = {
'ArticleID' => '86',
'OldTicketData' => {
'TicketID' => '67'

Following is the function in which I want to perform the mentioned operation:

sub PrepareRequest {
my ( $Self, %Param ) = @_;
my %TicketInfo = $Self->{TicketObject}->ArticleGet(
ArticleID => $Param{Data}->{ArticleID},
userID => $Param{Data}->{CustomerID},

my %newParamData = to_json($Param{Data});

return {
Success => 1,
Data => %newParamData,

Above function returns 'OldTicketData'. I want following key-pair attached to 'OldTicketData' element of the JSON object ->('Body', $TicketInfo{Body}). Consider, $TicketInfo{Body} returns a string 'someString'.

Answer Source

Your code is the wrong way around. You need to add the key to the hash reference first, before you turn it into JSON.

my $newParamData = to_json($Param{Data});

In addition, since to_json returns a string, which is scalar, you need to use $newParamData instead of %newParamData.

Of course you need to fix your return as well.

return {
    Success => 1,
    Data    => $newParamData,
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download