2016-09-29 28 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。我希望它对你也有帮助。 –