159

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...

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Tomas Aschan
  • 58,548
  • 56
  • 243
  • 402
  • 3
    Here are some nice plain JS solutions: http://stackoverflow.com/questions/1714786/querystring-encoding-of-a-javascript-object Some of them are not longer than the framwork solutions here. – Simon Steinberger May 10 '15 at 22:28

4 Answers4

250

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
Chris Laplante
  • 29,338
  • 17
  • 103
  • 134
79

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.

Rich Smith
  • 1,675
  • 12
  • 24
  • 1
    Cool, works! I've only added `if ( json[key] != null )` for omitting nulls – Valentin H Jul 23 '15 at 21:47
  • 1
    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
  • This works better than `$.param` because param encodes for forms not urls, so with param space becomes `+` instead of `%20` which can cause all kinds of issues, especially with MVC – NibblyPig Apr 24 '17 at 11:59
  • Using ES6 it's a pretty clean and neat solution for simple JavaScript objects https://gist.github.com/magician11/c16ae65cacd5cdb793f5f8215c1ef811 – magician11 Dec 17 '18 at 21:44
  • `jsonToQueryString({ query: true, options: { nested: true }})` is return object[Object] :( `?query=true&options=%5Bobject%20Object%5D` – Aral Roca Mar 22 '19 at 18:01
15

Another option might be node-querystring.

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

Valentin H
  • 7,240
  • 12
  • 61
  • 111
wprl
  • 24,489
  • 11
  • 55
  • 70
4

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);
Alex Stetsenko
  • 216
  • 1
  • 2
  • 7