Skip to content Skip to sidebar Skip to footer

Javascript Object (json) To Url String Format

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 n

Solution 1:

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){ 
  returnencodeURIComponent(key) + '=' + encodeURIComponent(obj[key]); 
}).join('&');

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

+1 @Pointy for encodeURIComponent

Post a Comment for "Javascript Object (json) To Url String Format"