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
Stringify a JavaScript ObjectUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.
toJSON() calls the object's toISOString() method, which returns a string representing the Date object's value. This method is generally intended to, by default, usefully serialize Date objects during JSON serialization, which can then be deserialized using the Date() constructor or Date. parse() as the reviver of JSON.
getElementById('output'). innerHTML = content; } // create script element var script = document. createElement('script'); // assing src with callback name script. src = 'http://url.to.json?callback=insertReply'; // insert script to document and load content document.
JSON is purely a string with a specified data format — it contains only properties, no methods. JSON requires double quotes to be used around strings and property names. Single quotes are not valid other than surrounding the entire JSON string.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With