JavaScript Object (JSON) to URL String Format

Owen picture Owen · Nov 11, 2013 · Viewed 23.1k times · Source

I've got a JSON object that looks something like

{
    "version" : "22",
    "who: : "234234234234"
}

And I need it in a string ready to be sent as a raw http body request.

So i need it to look like

version=22&who=234324324324

But It needs to work, for an infinite number of paramaters, at the moment I've got

app.jsonToRaw = function(object) {
    var str = "";
    for (var index in object) str = str + index + "=" + object[index] + "&";
    return str.substring(0, str.length - 1);
};

However there must be a better way of doing this in native js?

Thanks

Answer

Tibos picture Tibos · Nov 11, 2013

2018 update

var obj = {
    "version" : "22",
    "who" : "234234234234"
};

const queryString = Object.entries(obj).map(([key, value]) => {
    return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
}).join('&');

console.log(queryString); // "version=22&who=234234234234"

Original post

Your solution is pretty good. One that looks better could be:

var obj = {
    "version" : "22",
    "who" : "234234234234"
};

var str = Object.keys(obj).map(function(key){ 
  return encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]); 
}).join('&');

console.log(str); //"version=22&who=234234234234"

+1 @Pointy for encodeURIComponent