Convert JavaScript object into URI-encoded string

后端 未结 11 1363
庸人自扰
庸人自扰 2020-12-04 18:54

I got a JavaScript object which I would like to get x-www-form-urlencoded.

Something like $(\'#myform\').serialize() but for objects.

11条回答
  •  有刺的猬
    2020-12-04 19:34

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


    Answer 1:

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

    jsfiddle

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

    Result:

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

    Answer 2:

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

    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 

提交回复
热议问题