I'm trying to recreate a php process in Perl and am not having much luck ( I don't know much Perl ).
This is my php code:
$json = '{"0":{"name":"action","value":"none"},"1":{"name":"additionalTraining","value":"modulesRevisited"},"2":{"name":"additionalTrainingComments","value":""},"3":{"name":"additionalTraining","value":"moduleReporting"},"4":{"name":"additionalTrainingComments","value":""},"5":{"name":"additionalTrainingComments","value":""},"6":{"name":"anotherValue","value":""},"7":{"name":"1359436206","value":""},"8":{"name":"1359436207","value":""},"48":{"name":"actionId","value":""},"49":{"name":"multiSelect","value":"second"},"50":{"name":"multiSelect","value":"third"},"51":{"name":"radio","value":"1"},"52":{"name":"svgs","value":{"0":{"id":"drawing"},"1":{"id":"drawing"}}}}';
$decoded = json_decode($json,true);
$clean = array();
foreach($decoded as $Obj => $array){
if(array_key_exists($array['name'], $clean))
{
if(!is_array($clean[$array['name']]))
{
$value = $clean[$array['name']];
$clean[$array['name']] = array($value,$array['value']);
}
else
{
array_push($clean[$array['name']], $array['value']);
}
}
else
{
$clean[$array['name']]=$array['value'];
}
}
echo json_encode($clean);
UPDATE: This is what I've tried in Perl and the walls I keep hitting:
use JSON;
use Data::Dumper;
use warnings;
use strict;
my @records = decode_json($json_text);
foreach my $element (@records)
{
print "$element
";
}
I get a hashref. So I try changing the first line to:
my @records = @{ decode_json($json_text) }; #dereference function as it returns an arrayref, not a list
Then I get "Not an ARRAY reference" when trying to loop through.
Then I try something like this and get no results or errors:
my $records = decode_json($json_text);
my $i = 0;
my @records;
foreach my $entry (@{$records[0]}) {
my %listHash = %{$entry};
my $key;
my $value;
$i++;
while(($key, $value) = each(%listHash)) {
my $key;
my $value;
print "${key}_$i, $value
";
}
}
Then I try and combine bits of all of them to get the output I'm after and the closest I come to is:
my %records = %{ decode_json($json_text) };
while ( my ($key, $value) = each %records )
{
my $records;
#print "key: $key, value: $records{$key}
";
while ( my ($key, $value) = each %{$value} )
{
print "key: $key, value: $value
";
}
}
But this gives me output like so:
key: name, value: anotherValue
key: value, value: third
key: name, value: multiSelect
key: value, value: moduleReporting
whereas I need output like
key: anotherValue, value: third
key: multiSelect, value: moduleReporting
Where am I going wrong?
How can I recreate the same result in Perl? Your help is greatly appreciated.