This question already has an answer here:

I'm trying to find information on how to serialize an object to query string format, but all my searches are drowning in results on how to go the other way (string/form/whatever to JSON).

I have

{ one: 'first', two: 'second' }

and I want

?one=first&two=second

Is there a good way to do this? I don't mind plugins or whatnots - if the code I find is not a plugin, I'll probably re-write it to one anyway...

share|improve this question

marked as duplicate by Mogsdad, Tushar javascript Apr 19 at 3:51

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3  
Here are some nice plain JS solutions: stackoverflow.com/questions/1714786/… Some of them are not longer than the framwork solutions here. – Simon Steinberger May 10 '15 at 22:28
up vote 169 down vote accepted

You want $.param(): http://api.jquery.com/jQuery.param/

Specifically, you want this:

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

When given something like this:

{a: 1, b : 23, c : "te!@#st"}

$.param will return this:

a=1&b=23&c=te!%40%23st
share|improve this answer
7  
Note that if you have an array in your object it doesn't get parameterized correctly. – crv Apr 26 '12 at 19:46
2  
@crv: Right. JSON is probably best in that case – Chris Laplante Apr 28 '12 at 21:23
    
@crv I have an array in mine and it is working fine. – Danyal Aytekin Dec 4 '12 at 16:52
    
This won't work with asp.net 4.0 because of the & in the query string without you specifically setting your requestValidationMode="2.0" – Amicable Feb 26 '15 at 12:00

For a quick non-JQuery function...

function jsonToQueryString(json) {
    return '?' + 
        Object.keys(json).map(function(key) {
            return encodeURIComponent(key) + '=' +
                encodeURIComponent(json[key]);
        }).join('&');
}

Note this doesn't handle arrays or nested objects.

share|improve this answer
    
Cool, works! I've only added if ( json[key] != null ) for omitting nulls – Valentin Heinitz Jul 23 '15 at 21:47
    
This is a nice, JavaScript-only solution. One can assign the call to Object.keys to a params variable and return params.length && params.join('&') || "" for cases where the object might be empty, i.e., json={}. – t.888 Sep 17 '15 at 21:27

Another option might be node-querystring.

It's available in both npm and bower, which is why I have been using it.

share|improve this answer

Alternatively YUI has http://yuilibrary.com/yui/docs/api/classes/QueryString.html#method_stringify.

For example:

var data = { one: 'first', two: 'second' };
var result = Y.QueryString.stringify(data);
share|improve this answer
    
It is not maintained any more. – Valentin Heinitz Jul 23 '15 at 21:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.