Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Object (JSON) to URL String Format

Tags:

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

like image 261
owenmelbz Avatar asked Nov 11 '13 15:11

owenmelbz


People also ask

How do I encode a JSON string?

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.

What is toJSON () in JSON?

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.

How display JSON data from URL in HTML?

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.

What is a JSON string?

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.


1 Answers

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

like image 65
Tibos Avatar answered Oct 22 '22 15:10

Tibos