Skip to content

Instantly share code, notes, and snippets.

@lastguest
Created July 10, 2014 17:47
Show Gist options
  • Star 56 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • 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
*/
@smtchahal
Copy link

One liner using ES2015 (if you don't care about nesting or arrays):

const toUrlEncoded = obj => Object.keys(obj).map(k => encodeURIComponent(k) + '=' + encodeURIComponent(obj[k])).join('&');

toUrlEncoded({hello: 'world', message: "JavaScript is cool"});
// => "hello=world&message=JavaScript%20is%20cool"

@mdere-unbound
Copy link

mdere-unbound commented Mar 8, 2019

I have an issue when the object is further nested than your example for when a key has a value of null. What is the best way to make sure to ensure null value is included the key/value param?

@GiraffeSummer
Copy link

Thanks a ton, this really saved me!

@amiratak88
Copy link

This is great, Thanks a lot!

@Booligoosh
Copy link

Thanks for this!!! 🙏

@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