2016-09-29 25 views
-2

我想將深JSON轉換爲URL參數字符串。我已經JSON:如何將JSON深層對象轉換爲JavaScript中的URL參數?

{ filter: { dir: 184}, b:'a'} 

{ filter: [1,2,3], b:'a'} 

所以我想要的結果字符串是這樣的:

filter[dir]=188&b=a 
filter[]=1&filter[]=2&filter[]=3&b=a 

如何做到這一點在JavaScript(不jQuery的)?

+1

好像很簡單的規則,應該是一個循環和一些思考相當容易,建設字符串作爲你循環。試試看,如果卡住了,請回復一些嘗試的代碼 – musefan

+0

我知道。但我問了一個問題,並且已經準備好解決問題了。你有嗎? –

+1

謝謝大家。我在這裏找到了解決方案http://stackoverflow.com/questions/1714786/querystring-encoding-of-a-javascript-object –

回答

1

你可以使用迭代和遞歸風格的值。

function getString(o) { 
 

 
    function iter(o, path) { 
 
     if (Array.isArray(o)) { 
 
      o.forEach(function (a) { 
 
       iter(a, path + '[]'); 
 
      }); 
 
      return; 
 
     } 
 
     if (o !== null && typeof o === 'object') { 
 
      Object.keys(o).forEach(function (k) { 
 
       iter(o[k], path + '[' + k + ']'); 
 
      }); 
 
      return; 
 
     } 
 
     data.push(path + '=' + o); 
 
    } 
 

 
    var data = []; 
 
    Object.keys(o).forEach(function (k) { 
 
     iter(o[k], k); 
 
    }); 
 
    return data.join('&'); 
 
} 
 

 
var data1 = { filter: { dir: 184 }, b: 'a' }, 
 
    data2 = { filter: [1, 2, 3], b: 'a' }, 
 
    data3 = { filter: [1, 2, 3], b: 'a', c: { d: { e: 42 } } }; 
 

 
console.log(getString(data1)); 
 
console.log(getString(data2)); 
 
console.log(getString(data3));
.as-console-wrapper { max-height: 100% !important; top: 0; }

+1

喜歡那個控制檯顯示黑客;)另外,因爲你已經使它遞歸,所以我覺得我應該把你的選票投給我......悲傷的時候:( – musefan

+0

謝謝你,最好的解決方案在這裏http://stackoverflow.com/問題/ 1714786 /查詢字符串編碼對的一的JavaScript對象 –

0

好的,所以我其實對這個問題很感興趣,並想嘗試自己解決它。這意味着我可能也只是張貼這裏的解決方案,如果它可以幫助人們:

function build(input) { 
 
    var output = ""; 
 

 
    // Loop each property in the base object. 
 
    for (var p in input) { 
 
    var item = input[p]; 
 

 
    // Need to handle differently for Array, Object, and OTHER. 
 
    if (item instanceof Array) { 
 
     // Loop each array value and append to output. 
 
     for (var x in item) { 
 
     output += "&" + p + "[]=" + item[x]; 
 
     } 
 
    } else if (item instanceof Object) { 
 
     // Loop each sub object property and append to output. 
 
     // NOTE: We assume only a single level of object depth, this is NOT a recursive solution. 
 
     for (var x in item) { 
 
     output += "&" + p + "[" + x + "]=" + item[x]; 
 
     } 
 
    } else { 
 
     // Any other object type is just appended to output as is. 
 
     output += "&" + p + "=" + item; 
 
    } 
 
    } 
 

 
    // Finally, if we have any output, trim the first leading '&' character. 
 
    if (output.length > 0) 
 
    output = output.substring(1); 
 

 
    return output; 
 
} 
 

 
console.log(build({ filter: { dir: 184}, b:'a'})); 
 
console.log(build({ filter: [1,2,3], b:'a'}));
.as-console-wrapper { max-height: 100% !important; top: 0; }

+0

謝謝。而已!但我發現最好的解決方案是在這裏:http://stackoverflow.com/questions/1714786/querystring-encoding-of-a-javascript-object。我希望它對你也有幫助。 –