I got a JavaScript object which I would like to get x-www-form-urlencoded
.
Something like $(\'#myform\').serialize()
but for objects.
You need to use JSON.stringify()
to serialize the JSON/JavaScript object.
It is natively available in almost all the modern browsers but you can include the below js which will add the required library incase it is not available.
http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js
Since you were asking for a serialized object, this is probably slightly off the mark. But just in case, if your intent is to use the values within that object as individual parameters, this might be the conversion you're looking for:
var params = {
"param1": "arg1",
"param2": "arg2"
};
var query = "";
for (key in params) {
query += encodeURIComponent(key)+"="+encodeURIComponent(params[key])+"&";
}
xmlhttp.send(query);
Same as above in effect, but functional style gives an elegant expression::
const to_encoded = obj => Object.keys(obj).map(k =>
`${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`).join('&');
To build on @Claymore's answer, Here is a function to encode an object and additionally omit the trailing ampersand:
encodeObject(params) {
var query = [];
for (let key in params) {
let val = encodeURIComponent(key) + "=" + encodeURIComponent(params[key]);
query.push(val);
}
return query.join('&');
}
function jsonToURI(jsonObj) {
var output = '';
var keys = Object.keys(jsonObj);
keys.forEach(function(key) {
output = output + key + '=' + jsonObj[key] + '&';
})
return output.slice(0, -1);
}
function uriToJSON(urijson) {
var output = {};
urijson = decodeURIComponent(urijson);
urijson = urijson.split('&');
urijson.forEach(function(param) {
var param = param.split('=');
output[param[0]] = param[1];
})
return output
}