将JSON转换为uri编码的字符串

jga*_*fin 42 javascript jquery

我有一个JSON/javascript对象,我想得到x-www-form-urlencoded.

$('#myform').serialize()物体一样的东西.

以下对象:

{
    firstName: "Jonas",
    lastName: "Gauffin"
}
Run Code Online (Sandbox Code Playgroud)

将被编码为:

firstName=Jonas&lastName=Gauffin (请注意特殊字符应正确编码)

Gra*_*len 54

请仔细查看我在这里提供的两个答案,以确定最适合您的答案.


答案1:

可能你需要的东西:将一个JSON用作URL中的一个参数,以便以后解码.

的jsfiddle

encodeURIComponent(JSON.stringify({"test1":"val1","test2":"val2"}))+"<div>");
Run Code Online (Sandbox Code Playgroud)

结果:

%7B%22test%22%3A%22val1%22%2C%22test2%22%3A%22val2%22%7D
Run Code Online (Sandbox Code Playgroud)

对于那些只想要一个功能的人来说:

function jsonToURI(json){ return encodeURIComponent(JSON.stringify(json)); }

function uriToJSON(urijson){ return JSON.parse(decodeURIComponent(urijson)); }
Run Code Online (Sandbox Code Playgroud)

答案2:

使用JSON作为x-www-form-urlencoded输出的键值对的来源.

的jsfiddle

// This should probably only be used if all JSON elements are strings
function xwwwfurlenc(srcjson){
    if(typeof srcjson !== "object")
      if(typeof console !== "undefined"){
        console.log("\"srcjson\" is not a JSON object");
        return null;
      }
    u = encodeURIComponent;
    var urljson = "";
    var keys = Object.keys(srcjson);
    for(var i=0; i <keys.length; i++){
        urljson += u(keys[i]) + "=" + u(srcjson[keys[i]]);
        if(i < (keys.length-1))urljson+="&";
    }
    return urljson;
}

// Will only decode as strings
// Without embedding extra information, there is no clean way to
// know what type of variable it was.
function dexwwwfurlenc(urljson){
    var dstjson = {};
    var ret;
    var reg = /(?:^|&)(\w+)=(\w+)/g;
    while((ret = reg.exec(urljson)) !== null){
        dstjson[ret[1]] = ret[2];
    }
    return dstjson;
}
Run Code Online (Sandbox Code Playgroud)

  • @monarch:因为它没有编码为x-www-form-urlencoded(键值对). (14认同)
  • 这应该是标准答案.不知道为什么没有人赞成这个. (2认同)

jb1*_*210 20

jQuery.param(...).转换为uri,请参阅链接以获取更多信息!


Cla*_*ore 17

既然你要求一个序列化的对象,这可能略微偏离了标记.但为了以防万一,如果您的意图是将该对象中的值用作单个参数,这可能是您正在寻找的转换:

var params = {
    "param1": "arg1",
    "param2": "arg2"
};
var query = "";
for (key in params) {
    query += encodeURIComponent(key)+"="+encodeURIComponent(params[key])+"&";
}
xmlhttp.send(query);
Run Code Online (Sandbox Code Playgroud)


小智 11

我很惊讶没有人提到 URLSearchParams

var prms = new URLSearchParams({
  firstName: "Jonas",
  lastName: "Gauffin"
});
console.log(prms.toString());
// firstName=Jonas&lastName=Gauffin
Run Code Online (Sandbox Code Playgroud)

  • 绝对应该是公认的答案。只知道它在 IE 中不起作用。检查 CanIUse 以了解是否已更改:https://caniuse.com/#search=URLSearchParams (3认同)