Search code examples
htmlperlhashdancer

parse form (POST) data to create a multidimensional hash


I have a form which is used to submit data about multiple people. There are multiple properties for each person, and I'm grouping them like the following:

<input type=hidden name="person1[firstname]" value='Sam'/>
<input type=hidden name="person1[lastname]" value='Higgins'/>

<input type=hidden name="person2[firstname]" value='Jiminy'/>
<input type=hidden name="person2[lastname]" value='Cricket'/>

...etc

When I do the following:

my %hash = params;
die Dumper \%hash;

I get:

VAR1 = {
          'person1[firstname]' => 'Sam',
          'person1[lastname]' => 'Higgins',
          'person2[firstname]' => 'Jiminy',
          'person2[lastname]' => 'Cricket',
};

When I was expecting something like:

VAR1 = {
          'person1' => { firstname => 'Sam', lastname => 'Higgens' },
          'person2' => { firstname => 'Jiminy', lastname => 'Cricket' },
};

Is there a way to get the above, or am I doing it wrong in my HTML?

Edit

I've also tried with empty brackets at the end:

<input type=hidden name="person1[firstname][]" value='Sam'/>

but that just gave:

'person1[firstname][]' => 'Sam',

Solution

  • To answer the question more wholly than providing a link:

    I went with a solution that uses jQuery, specifically using a plugin (https://github.com/marioizquierdo/jquery.serializeJSON), to send the data asynchronously (AJAX) and using Dancers from_json method which creates a hashref of the JSON string.

    I emphasise string because the function offered by the serializeJSON plugin creates a JSON object, and this Dancer does not convert to the proper structure. Therefore you need to use JSON.stringify() to create a json string, which Dancer does accept :)

    Below is the code:

    Example HTML:

    <input type=hidden name="person1[firstname]" value='Sam'/>
    <input type=hidden name="person1[lastname]" value='Higgins'/>
    

    JS (jQuery):

    var formData = $(this).serializeJSON();
    console.log(formData);
    $.ajax({
         'url': '/your_url',
         'type': 'POST',
         'data': JSON.stringify(formData),
         'success': function(res){
             console.log(res);
       }
     });
    

    Perl (Dancer):

    post '/your_url' => sub {
        my $json = request->body;
        use Data::Dumper;
        my $hashref = {};
        $hashref = from_json($json);
        die Dumper \$hashref->{person1}->{name}; # 'Sam'
    }
    

    Thanks to all who helped!