handle incoming multidimensional array/JSON ?

117 views
Skip to first unread message

Josef Richter

unread,
Oct 29, 2009, 9:51:02 PM10/29/09
to sinatrarb
Hello,

I need to send a 2-dimensional array from javascript/jquery to
sinatra. I formated the data into a JSON object as you can see here,
together with the sending ajax function:

function send_data() {
var testdata = {
"1": {
"name": "client_1",
"note": "bigboy"
},
"2": {
"name": "client_2",
"note": "smallboy"
}
}

console.log(testdata);
$.ajax({
type: 'POST',
url: 'test',
dataType: 'json',
data: testdata
});
}


http://pastie.org/676014

I am unable to pick it up correctly on ruby side, though. The best I
could get was {"1"=>"[object Object]", "2"=>"[object Object]"}.

The sinatra side is pretty basic at the moment:

...
require 'json'

...

post '/test' do
pp params
end

I think I am messing the stringify/parse logic here. But when I tried
adding stringify on js side and parse on ruby side, I was getting
things like {"{\"1\":{\"name\":\"client_1\",\"note\":\"bigboy\"},\"2\":
{\"name\":\"client_2\",\"note\":\"smallboy\"}}"=>nil}

Maybe could someone post a very brief example of sending a 2d array
from js to sinatra, please? The opposite way should be easier,
with .to_json on ruby side and JSON.parse() on js side, right?

Thank you very much. I already spent 8 hours on this piece and am
completely lost :-(

Josef Richter

Damian Janowski

unread,
Oct 30, 2009, 1:13:15 AM10/30/09
to sina...@googlegroups.com
On Thu, Oct 29, 2009 at 10:51 PM, Josef Richter <richte...@gmail.com> wrote:
>
> Hello,
>
> I need to send a 2-dimensional array from javascript/jquery to
> sinatra. I formated the data into a JSON object as you can see here,
> together with the sending ajax function:
>
> function send_data() {
>        var testdata = {
>            "1": {
>                "name": "client_1",
>                "note": "bigboy"
>            },
>            "2": {
>                "name": "client_2",
>                "note": "smallboy"
>            }
>        }
>
>        console.log(testdata);
>        $.ajax({
>          type: 'POST',
>          url: 'test',
>          dataType: 'json',
>          data: testdata
>        });
>      }

data needs to be a string to be sent with the POST request. You'll
need something like $.toJSON [1], which is not built into jQuery.

[1] http://www.overset.com/2008/04/11/mark-gibsons-json-jquery-updated/

Reply all
Reply to author
Forward
0 new messages