HTML Form: POST an array of objects HTML Form: POST an array of objects arrays arrays

HTML Form: POST an array of objects


tl;dr: Add empty brackets ([]) after students to the input names.

Fiddling with Rack::Utils.parse_nested_query it seems you can get the payload you want like this:

<!-- first student --><input type="text" name="students[][first]"><input type="text" name="students[][last]"><input type="text" name="students[][age]"><!-- second student --><input type="text" name="students[][first]"><input type="text" name="students[][last]"><input type="text" name="students[][age]">

Note the empty brackets ([]) after students. This tells Rack you want the students param to be an array. Subsequent params encountered (with the same name) will start a new element.

POST /myroute?students[][first]=foo&students[][last]=bar&students[][age]=21&students[][first]=baz&students[][last]=qux&students[][age]=19

Gets parsed like this:

{"students" => [  {    "first" => "foo",     "last" => "bar",      "age" => "21"  },  {    "first" => "baz",     "last" => "qux",      "age" => "19"  }]}

Further reading: http://codefol.io/posts/How-Does-Rack-Parse-Query-Params-With-parse-nested-query


I know the question is old , but I would like to add my experiences also for future readers.

For those of you who want to process the data in a PHP enviroment ,@messanjah's method won't work ,

The methods for parsing data like the built-in serializeArray or serialize are not parsing it as expected either.

This is what I tried so far ...

  • students[name]
  • students[][name] - Very Strange since it was meant to automatically index the array
  • students[name][]

Neither of them worked, but this students[<hardcoded-index>][name] worked for PHP ,

I know that although the question is against this method , but it will be useful for PHP users who will land here in the nearby future as the asker needed it for Ruby On Rails.

The method you choose to hard code the indexes is upto you , you can use a cleaner method by using javascript or you can manually hard code them initially in your form element.

Cheers