How do I turn this...
{
'name': 'John',
'surname': 'Smith'
}
...into this?
name=John&surname=Smith
I'm trying to send JSON to a server via AJAX
thank you
var jsoncode = {
'name': 'John',
'surname': 'Smith'
};
var querystring = 'name=' + encodeURI(jsoncode.name) + '&surname=' + encodeURI(jsoncode.surname);
Gernerically (i.e. without any JS framework)...
var o = {'name': 'John', 'surname': 'Smith'};
var q = [];
for (p in o) {
if (o.hasOwnProperty(p)) {
q.push( encodeURIComponent(p) + "=" + encodeURIComponent(o[p]) );
}
}
q = q.join("&"); // "name=John&surname=Smith"
As people in comments already noted, this would work for flat, non-nested objects only. For advanced uses, I strongly recommend doing an HTTP post operation and sending the object unmodified as a JSON string.
All JS libraries provide a way to transform an object to JSON, and there are other ways to serialize an object, like Douglas Crockford's own implementation at http://json.org/js.html.
There a number of ways to do this, but probably the easiest is to write an iterator for your object:
var propstr = "?";
for (prop in jsonCode) {
if (jsonCode.hasOwnProperty(prop)) {
propstr += prop + "=" + jsonCode[prop] + "&"
}
}
First, are you using any javascript library? (jquery, prototype, etc...). If you are there are functions to do this somewhere in there.
Otherwise you could use something like:
var urlParams = '?';
var index = 0;
for(var key in obj){
If(index != 0) urlParams += '&';
urlParams += key + '='+obj[key];
}