jsonperlmason

Accessing Json objects in perl and reuse it in another JSON


I have received arguments in my mason handler which looks in the following format:

$data = {
    'cacheParams' => 0,
    'requests' => {
        'locationId' => 1,
        'uniqueId' => [
            'ABC',
            'DEF',
            'XYZ'
        ]
    }
};

I am able to access the requests by using $data['requests']. How do I access the values stored in requests, i.e. locationId and uniqueId ? I need to use these values to form another JSON in the following way:

my $input = {
    stateID => 44,
    locationId => requests.locationId,
    uniqueId => requests.uniqueId
    .
    .
    .

}

Solution

  • The $data['requests'] object should be an hash in your way. So you can access to the keys like in the following:

    $data['requests']->{'locationId'}
    $data['requests']->{'uniqueId'}
    
    or 
    
    $requests = $data['requests']
    $locationId = $requests->{'locationId'}
    $uniqueId = $requests->{'uniqueId'}