Skip to content

Instantly share code, notes, and snippets.

@lastguest
Created July 10, 2014 17:47
Show Gist options
  • Save lastguest/1fd181a9c9db0550a847 to your computer and use it in GitHub Desktop.
Save lastguest/1fd181a9c9db0550a847 to your computer and use it in GitHub Desktop.
Convert JavaScript object to x-www-form-urlencoded format
function JSON_to_URLEncoded(element,key,list){
var list = list || [];
if(typeof(element)=='object'){
for (var idx in element)
JSON_to_URLEncoded(element[idx],key?key+'['+idx+']':idx,list);
} else {
list.push(key+'='+encodeURIComponent(element));
}
return list.join('&');
}
var data = {
'users' : [
{
"id": 100,
"name": "Stefano"
},
{
"id": 200,
"name": "Lucia"
},
{
"id": 300,
"name": "Franco"
},
],
'time' : +new Date
};
console.log(
JSON_to_URLEncoded(data)
);
/*
Output:
users[0][id]=100&users[0][name]=Stefano&users[1][id]=200&users[1][name]=Lucia&users[2][id]=300&users[2][name]=Franco&time=1405014230183
*/
@lastguest
Copy link
Author

import qs from 'querystring';
qs.stringify({ 'key': 'value' })

this worked really well for me.

The gist was from 7 years ago... hopefully things have improved since then 😅

@teezeit
Copy link

teezeit commented Aug 27, 2021

import qs from 'querystring';
qs.stringify({ 'key': 'value' })

this worked really well for me.

The gist was from 7 years ago... hopefully things have improved since then sweat_smile
not as much as you'd think :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment