Skip to content

Instantly share code, notes, and snippets.

@yoeven
Forked from lastguest/JSON_to_URLEncoded.js
Last active July 5, 2023 07:19
Show Gist options
  • Save yoeven/ab9c9b85056c601dd0782e90ad87191a to your computer and use it in GitHub Desktop.
Save yoeven/ab9c9b85056c601dd0782e90ad87191a to your computer and use it in GitHub Desktop.
Convert JavaScript object to x-www-form-urlencoded format
const JSONtoURLEncoded = (element: any, key?: string, _list?: any[]) => {
let list = _list || [];
if (typeof element == "object") {
for (let idx in element) JSONtoURLEncoded(element[idx], key ? key + "[" + idx + "]" : idx, list);
} else {
list.push(key + "=" + encodeURIComponent(element));
}
return list.join("&");
};
const 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
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment