JavaScript 函数将 JSON 键值对象转换为查询字符串

发布于 2024-10-17 08:52:34 字数 1153 浏览 8 评论 0 原文

我正在努力格式化 Facebook Feed Dialog 的网址。不过参数实在是太多了。我想要为这些对话框提供一个功能,例如:

function generateDialogUrl(dialog, params) {
  base  = "http://www.facebook.com/dialog/" + dialog + "?";
  tail = [];
  for (var p in params) {
    if (params.hasOwnProperty(p)) {
      tail.push(p + "=" + escape(params[p]));
    }
  }
  return base + tail.join("&")
}

哦哇...我想我刚刚回答了我自己的问题。是这样吗? escape() 是正确使用的函数吗?

我被困在情人源代码

更新:因为我们使用的是 jQuery,所以我使用 jQuery.each 重写了该方法。我还按照 @galambalazs & 的建议,用 encodeURIComponent() 替换了 escape() 。 @TJ克劳德。谢谢你们!

var generateDialogUrl = function (dialog, params) {
  base  = "http://www.facebook.com/dialog/" + dialog + "?";
  tail = [];
  $.each(params, function(key, value) {
    tail.push(key + "=" + encodeURIComponent(value));
  })
  return base + tail.join("&");
}

它正在工作!

I'm working on formatting a URL for the Facebook Feed Dialog. There's so many parameters though. I want to have a function for these dialogs, something like:

function generateDialogUrl(dialog, params) {
  base  = "http://www.facebook.com/dialog/" + dialog + "?";
  tail = [];
  for (var p in params) {
    if (params.hasOwnProperty(p)) {
      tail.push(p + "=" + escape(params[p]));
    }
  }
  return base + tail.join("&")
}

Oh wow... I think I just answered my own question. Is that right? Is escape() the correct function to use?

I'm stuck in the Lovers source code.

UPDATE: Since, we're using jQuery, I rewrote the method using jQuery.each. I also replaced escape() with encodeURIComponent() as suggested by @galambalazs & @T.J. Crowder. Thanks, guys!

var generateDialogUrl = function (dialog, params) {
  base  = "http://www.facebook.com/dialog/" + dialog + "?";
  tail = [];
  $.each(params, function(key, value) {
    tail.push(key + "=" + encodeURIComponent(value));
  })
  return base + tail.join("&");
}

It's working!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

盛装女皇 2024-10-24 08:52:34

更好的是,使用 encodeURIComponent 代替。请参阅这篇文章比较两者:

escape()方法不编码
被解释的 + 字符
也作为服务器端的空间
由带有空格的表单生成
他们的领域。由于这个缺点
事实上这个函数失败了
处理非 ASCII 字符
正确地,您应该避免使用
尽可能使用 escape() 。 最好的
替代方案通常是
encodeURIComponent()

escape() 不会编码:@*/+

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: @*/+

心的位置 2024-10-24 08:52:34

有一个 jQuery 方法可以完成此操作:$.param。它会像这样工作:

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

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);
}
提笔书几行 2024-10-24 08:52:34
const createQueryParams = (param, prefix = '') => {
    let queryString = '';
    if (param.constructor === Object) {
        queryString = Object.keys(param).reduce((result, key) => {
            const obj = param[key];
            const queryParam = result ? `${result}&${prefix}` : prefix;
            if (obj.constructor === Object) {
                return `${queryParam}${createQueryParams(obj, `${key}.`)}`;
            } else if(obj.constructor === Array) {
                const qp= obj.map((item, index)=> {
                    if (item.constructor === Object || item.constructor === Array) {
                        const query = createQueryParams(item, `${key}[${index}].`);
                        return `${query}`;
                    } else {
                        return `${key}[${index}]=${item}`;
                    }
                }).reduce((res, cur) => {
                    return res ? `${res}&${cur}`: `${cur}`;
                }, '');

                return `${queryParam}${qp}`;
            } else {
                return `${queryParam}${key}=${obj}`;
            }
        }, '');
    } else if(param.constructor === Array) {
        queryString = param.reduce((res, cur) => `${res},${cur}`);
    } else {
        queryString = param;
    }

    return encodeURI(queryString);
};

例子:

createQueryParams({"Context":{"countryCode":"NO"},"Pagination":{"limit":10,"offset":1},"AdditionalField":[{"name":"Policy Number","value":"Pol123"},{"name":"Policy Version","value":"PV1"}]});
const createQueryParams = (param, prefix = '') => {
    let queryString = '';
    if (param.constructor === Object) {
        queryString = Object.keys(param).reduce((result, key) => {
            const obj = param[key];
            const queryParam = result ? `${result}&${prefix}` : prefix;
            if (obj.constructor === Object) {
                return `${queryParam}${createQueryParams(obj, `${key}.`)}`;
            } else if(obj.constructor === Array) {
                const qp= obj.map((item, index)=> {
                    if (item.constructor === Object || item.constructor === Array) {
                        const query = createQueryParams(item, `${key}[${index}].`);
                        return `${query}`;
                    } else {
                        return `${key}[${index}]=${item}`;
                    }
                }).reduce((res, cur) => {
                    return res ? `${res}&${cur}`: `${cur}`;
                }, '');

                return `${queryParam}${qp}`;
            } else {
                return `${queryParam}${key}=${obj}`;
            }
        }, '');
    } else if(param.constructor === Array) {
        queryString = param.reduce((res, cur) => `${res},${cur}`);
    } else {
        queryString = param;
    }

    return encodeURI(queryString);
};

Example:

createQueryParams({"Context":{"countryCode":"NO"},"Pagination":{"limit":10,"offset":1},"AdditionalField":[{"name":"Policy Number","value":"Pol123"},{"name":"Policy Version","value":"PV1"}]});
惯饮孤独 2024-10-24 08:52:34
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;
};

示例:

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

结果:

"Name=1Children[0].Age=1Children[1].Age=2&Children[1].Hoobbie=eatInfo.Age=1&Info.Height=80"
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"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文