views:

162

answers:

1

I'm trying to find information on how to serialize a JSON 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...

+5  A: 

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

Specifically, you want this:

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

The decodeURIComponent function searches the given string for escape sequences and replaces them with the actual character.

When given something like this:

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

$.param will return this:

a=1&b=23&c=te!%40%23st

If you don't want the escape sequences, decodeURIComponent is used. The result, using my original suggestion, is this:

a=1&b=23&c=te!@#st

Pure $.param is safe for when you don't have characters such as + and ? in your data. Otherwise, use the second version. I hope that has clarified things.

SimpleCoder
Wait - you probably **don't** want to call "decodeURIComponent". jQuery will already encode the parameter names and values. If you *decode* the whole string, it won't work as a parameter string anymore.
Pointy
Tomas Lycken
@Pointy and @user399050: See edited answer
SimpleCoder