1

I want to send a javascript array to a rails application using jquery

$.ajax
  url: 'some url'
  data: {list: [{id: 4, name: 'John'}, {id: 5, name: 'Locke'}]}
  method: 'post'
  dataType: 'json'

The problem with this method is that it serialize as follows:

list[0][id]=4&list[0][name]=John&... so on

Leading, on the Rails side to something like

    {"list"=>
      {
        "0"=>{"id"=>"4", "name"=>"John"},
        "1"=>{"id"=>"5", "name"=>"Locke"}
      }
     }

While I'd like to get something like

      {"list"=>
        [
          {"id"=>"4", "name"=>"John"},
          {"id"=>"5", "name"=>"Locke"}
        ]
       }

( Notice the inner list instead of a inner hash )

Is there a clean pretty way to send the data in a way rails would recognize it?

(PS: The view was not generated by rails, it is a phonegap mobile app)

This question jQuery posting JSON has little to do with my problem.

My problem is to serialize in a particular way, while the question is about how to serialize at all.

Community
  • 1
  • 1
Pedro Bernardes
  • 706
  • 1
  • 8
  • 20

1 Answers1

2

I see two options for you:

One, as others have suggested, use JSON.stringify() / JSON.generate() in your AJAX call. Yes, Rails will get your data as a single string, but that's okay. Use JSON.parse() once you receive the data to turn it back into JSON.

Two, just iterate through it anyway:

h = {"list"=>
      {
        "0"=>{"id"=>"4", "name"=>"John"},
        "1"=>{"id"=>"5", "name"=>"Locke"}
      }
     }

h['list'].each do |elem|
  value = elem[1]
end

# => {"id"=>"4", "name"=>"John"}
# => {"id"=>"5", "name"=>"Locke"}

Upon each iteration, value will be each element in your original array.

XML Slayer
  • 1,530
  • 14
  • 31