0

I am sending an array ("[1,3,44,2,0]") via an Ajax PATCH call, and it arrives as:

Parameters: {"ids"=>"[1,3,44,2,0]"}

To taint check, I am using the following line - in which the match anchors against the start and end of the string, and makes sure that there is at least one digit, or that the numbers are comma separated:

raise "unexpected ids #{params[:ids]}" unless params[:ids].match(/\A\[(\d+,)*\d+\]\z/)

And to make an actual integer array out of it, I am using the following approach (strip the brackets, split on comma, convert each string element to an integer):

irb> "[1,3,44,2,0]"[1...-1].split(',').map {|e| e.to_i}
 => [1, 3, 44, 2, 0]

Is there a better (simpler, cheaper, faster) way of doing this?

1 Answer 1

1

Try

JSON.parse(params[:ids])

But I think you should check your Ajax call. It must be possible to pass the array not as a string.

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

1 Comment

Thank you! My bad! I just checked the Ajax call, and though I wanted to pass the array as an integer array, I was actually calling JSON.stringify on it. I totally forgot about that - and I did it because I read someone recommending that approach. Was that a bad recommendation (to stringify)?? Is there nothing wrong with just passing an array of integers?

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.