参考自 复杂js对象转url参数字符串 - 开源中国社区 并做了优化

函数

var parseJson2Url = function (param, key) {
  var paramStr = '';
  var mappingOperator = '=';
  var separator = '&';
  if (param instanceof String || typeof (param) == 'string' || param instanceof Number || typeof (param) == 'number' || param instanceof Boolean || typeof (param) == 'boolean') {
    paramStr += separator + key + mappingOperator + encodeURIComponent(param);
  } else {
    for (var i in param) {
      var value = param[i];
      var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
      paramStr += separator + parseJson2Url(value, k);
    }
  }
  return paramStr.substr(1);
};

测试

var json = {'a': 'aaa', 'b': ['b1', 'b2', 'b3'], 'c': [1, new Number(2), new Boolean(3)], 'd': '中文', 'e': {'da': 'dddaaa'}}
var result1 = parseJson2Url(json, 'xyz');
var result2 = parseJson2Url(json);
console.info('result1: ' + result1);
console.info('result2: ' + result2);

测试结果

result1: xyz.a=aaa&xyz.b[0]=b1&xyz.b[1]=b2&xyz.b[2]=b3&xyz.c[0]=1&xyz.c[1]=2&xyz.c[2]=true&xyz.d=%E4%B8%AD%E6%96%87&xyz.e.da=dddaaa
result2: a=aaa&b[0]=b1&b[1]=b2&b[2]=b3&c[0]=1&c[1]=2&c[2]=true&d=%E4%B8%AD%E6%96%87&e.da=dddaaa
About Me
WEB开发工程师
GitHub Repos