JavaScript: Serialize JSON object to a query string

JavaScript (of course nested objects would require more efforts)

var data = { one: 'first', two: 'second' };
var result = '';
for(key in data) {
    result += key + '=' + data[key] + '&';
}
result = result.slice(0, result.length - 1); 
console.log(result);

jQuery (api.jquery.com/jQuery.param/)

var data = { one: 'first', two: 'second' };
var result = $.param(data);
console.log(result);

YUI (yuilibrary.com/yui/docs/api/classes/QueryString.html#method_stringify)

var data = { one: 'first', two: 'second' };
var result = Y.QueryString.stringify(data);
console.log(result);

No Comment

No comments yet

Leave a reply