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
*/
@ntohidi
Copy link

ntohidi commented Oct 11, 2019

Thanks a lot, this saved my day!

@clshortfuse
Copy link

clshortfuse commented Oct 22, 2019

Slightly faster with Object.entries() than Object.keys() because you get both the value back as well per iteration.

/**
 * @param {Object} object
 * @return {string}
 */
export function toFormUrlEncoded(object) {
  return Object.entries(object)
    .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
    .join('&');
}

@bitterloa
Copy link

@clshortfuse I used your code successfully to create the params string necessary to properly send data to Rails using the Rails.ajax() javascript library.

@ezragol
Copy link

ezragol commented Apr 18, 2020

This is amazing! Thanks so much!

@ProgramFilesx86
Copy link

Saved my day , Thanks a lot ♥

@aayla-secura
Copy link

That's great, thanks. Based on your version, I wrote one in python which encodes the keys as well and with optional arguments to select safe characters (which should not be encoded).

@arrudacaio
Copy link

Saved my life, thank you!! <3

@sevillaarvin
Copy link

Slightly faster with Object.entries() than Object.keys() because you get both the value back as well per iteration.

/**
 * @param {Object} object
 * @return {string}
 */
export function toFormUrlEncoded(object) {
  return Object.entries(object)
    .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
    .join('&');
}

Does not produce the same output when:

x = {a: 1, b: { c: 3, d: "asdf & hahaha" }}

JSON_to_URLEncoded(x)
// "a=1&b[c]=3&b[d]=asdf%20%26%20hahaha"

toFormUrlEncoded(x)
// "a=1&b=%5Bobject%20Object%5D"

@clshortfuse
Copy link

@sevillaarvin It's a modified version of https://gist.github.com/lastguest/1fd181a9c9db0550a847#gistcomment-2643755

The original has a custom object nesting algorithm. There's no official standard for converting Object to string values. URLSearchParams are always string values. Convert your nested objects to string beforehand or line (eg: with JSON.stringify(value))

@teezeit
Copy link

teezeit commented Jun 3, 2021

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

this worked really well for me.

@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