win5rx win5rx - 6 months ago 29
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});
%newParamData->{'OldTicketData'}->{'Body'}=$TicketInfo{Body};

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

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

$Param{Data}->{'OldTicketData'}->{'Body'}=$TicketInfo{Body};
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,
};