且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-23 10:58:25

请仔细查看我在此处提供的两个答案,以确定最适合您的答案。

Please look closely at both answers I provide here to determine which fits you best.

您可能需要的东西:将URL中的JSON作为单个参数进行准备,以便以后解码。

Likely what you need: Readies a JSON to be used in a URL as a single argument, for later decoding.

jsfiddle

jsfiddle

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

结果:

%7B%22test%22%3A%22val1%22%2C%22test2%22%3A%22val2%22%7D

对于那些只想要一个函数的人来说:

For those who just want a function to do it:

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

function uriToJSON(urijson){ return JSON.parse(decodeURIComponent(urijson)); }






答案2:



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


Answer 2:

Uses a JSON as a source of key value pairs for x-www-form-urlencoded output.

jsfiddle

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;
}