JavaScript function to convert JSON key-value object to query string JavaScript function to convert JSON key-value object to query string json json

JavaScript function to convert JSON key-value object to query string


Better yet, use encodeURIComponent instead. See this article comparing the two:

The escape() method does not encode the + character which is interpreted as a space on the server side as well as generated by forms with spaces in their fields. Due to this shortcoming and the fact that this function fails to handle non-ASCII characters correctly, you should avoid use of escape() whenever possible. The best alternative is usually encodeURIComponent().

escape() will not encode: @*/+


There is a jQuery method to accomplish this: $.param. It would work like this:

var generateDialogUrl = function (dialog, params) {  base = 'http://www.facebook.com/dialog/' + dialog + '?';  return base + $.param(params);}


convertJsonToQueryString: function (json, prefix) {    //convertJsonToQueryString({ Name: 1, Children: [{ Age: 1 }, { Age: 2, Hoobbie: "eat" }], Info: { Age: 1, Height: 80 } })    if (!json) return null;    var str = "";    for (var key in json) {        var val = json[key];        if (isJson(val)) {            str += convertJsonToQueryString(val, ((prefix || key) + "."));        } else if (typeof (val) == "object" && ("length" in val)) {            for (var i = 0; i < val.length; i++) {                //debugger                str += convertJsonToQueryString(val[i], ((prefix || key) + "[" + i + "]."));            }        }        else {            str += "&" + ((prefix || "") + key) + "=" + val;        }    }    return str ? str.substring(1) : str;}isJson = function (obj) {    return typeof (obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;};

example:

convertJsonToQueryString({Name:1,Children:[{Age:1},{Age:2,Hoobbie:"eat"}],Info:{Age:1,Height:80}})

Result:

"Name=1Children[0].Age=1Children[1].Age=2&Children[1].Hoobbie=eatInfo.Age=1&Info.Height=80"