Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass array as query string

I'm attempting to pass an array to my server via jsonp - here's a JSON example of what I'm trying to pass:

["something","another_thing",4,{"iam" : "anobject"}]

However, I'm not sure how (if it's possible) to pass an array.

I assumed it would be like this:

something&another_thing&4&[iam]=anobject

but when I pass that to querystring.parse() in node, it gives me this:

{ '4': '',
  something: '',
  another_thing: '',
  '[iam]': 'anobject' }

That's definitely not what I want. I can just use JSON, but this is now something I'm wondering if is possible.

like image 725
Jesse Avatar asked Dec 21 '22 15:12

Jesse


1 Answers

If you want to pass that data structure using PHP's URI format (which is what your attempt looks like), it would look something like:

data[0]=something&data[1]=another_thing&data[2]=4&data[3][iam]=anobject

You are probably better off just passing the JSON itself though. Take the JavaScript object and run it through JSON.stringify() and encodeURIComponent() to get:

data=something%2Canother_thing%2C4%2C%5Bobject%20Object%5D

Then you would use querystring.parse(), extract the data parameter from it, then run JSON.parse() on that value.

like image 199
Quentin Avatar answered Jan 05 '23 00:01

Quentin