160

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

1

4 Answers 4

252

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
Sign up to request clarification or add additional context in comments.

6 Comments

Note that if you have an array in your object it doesn't get parameterized correctly.
@crv: Right. JSON is probably best in that case
@crv I have an array in mine and it is working fine.
This won't work with asp.net 4.0 because of the & in the query string without you specifically setting your requestValidationMode="2.0"
It doesn't handle nested objects correctly.
|
80

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.

5 Comments

Cool, works! I've only added if ( json[key] != null ) for omitting nulls
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={}.
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
Using ES6 it's a pretty clean and neat solution for simple JavaScript objects gist.github.com/magician11/c16ae65cacd5cdb793f5f8215c1ef811
jsonToQueryString({ query: true, options: { nested: true }}) is return object[Object] :( ?query=true&options=%5Bobject%20Object%5D
15

Another option might be node-querystring.

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

Comments

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);

1 Comment

It is not maintained any more.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.