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.

5
  • 2
    possible duplicate of jQuery posting JSON Commented Aug 3, 2015 at 21:16
  • Convert the data to json with JSON.stringify(obj). All modern clients (and IE8) support it natively. Commented Aug 3, 2015 at 21:24
  • Now jQuery interprets "data" as a single string, as the Rails server. Commented Aug 3, 2015 at 21:27
  • JSON.stringify(obj) may not be answer! Commented Aug 3, 2015 at 21:27
  • Yes, data is a single string according to both the server and jQuery; make sure the rails server knows that the content type is json (either using content type headers or format: :json or appending .json to the link) Commented Aug 3, 2015 at 21:38

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.