Serialize object to query string in JavaScript/jQuery

153,512

Solution 1

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

Solution 2

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.

Solution 3

Another option might be node-querystring.

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

Solution 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);
Share:
153,512

Related videos on Youtube

Tomas Aschan
Author by

Tomas Aschan

I am an engineering physicist from Stockholm, Sweden, with a passionate interest in programming and software architecture. Since creating my first program at age 12 (a VB6 app that showed a smiley when a button was clicked) I've spent many hours in front of my computer, watching screen casts and reading blogs about programming as well as trying all the new concepts out in my own programs. With a Master's degree in Engineering Physics from the Royal Institute of Technology in Stockholm, Sweden, I have deepened my modelling and reasoning skills, as well as had the opportunity to try out many different technologies and tools. I am currently working as a software engineer at Spotify, mostly massaging data to enable our internal research into developer productivity.

Updated on April 19, 2020

Comments

  • Tomas Aschan
    Tomas Aschan about 4 years

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

  • crv
    crv about 12 years
    Note that if you have an array in your object it doesn't get parameterized correctly.
  • Chris Laplante
    Chris Laplante about 12 years
    @crv: Right. JSON is probably best in that case
  • Danyal Aytekin
    Danyal Aytekin over 11 years
    @crv I have an array in mine and it is working fine.
  • Amicable
    Amicable about 9 years
    This won't work with asp.net 4.0 because of the & in the query string without you specifically setting your requestValidationMode="2.0"
  • Valentin H
    Valentin H almost 9 years
    It is not maintained any more.
  • Valentin H
    Valentin H almost 9 years
    Cool, works! I've only added if ( json[key] != null ) for omitting nulls
  • t.888
    t.888 over 8 years
    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={}.
  • NibblyPig
    NibblyPig about 7 years
    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
  • newman
    newman almost 6 years
    It doesn't handle nested objects correctly.
  • magician11
    magician11 over 5 years
    Using ES6 it's a pretty clean and neat solution for simple JavaScript objects gist.github.com/magician11/c16ae65cacd5cdb793f5f8215c1ef811
  • Aral Roca
    Aral Roca about 5 years
    jsonToQueryString({ query: true, options: { nested: true }}) is return object[Object] :( ?query=true&options=%5Bobject%20Object%5D