a.b=3&b[0]=1&c=d" /> a.b=3&b[0]=1&c=d - 秒客网" />

把json格式对象转成可提交字符串格式,会过滤掉函数 {a: {b: 3}, b: [1], c: "d"} -> a.b=3&b[0]=1&c=d

时间:2023-03-09 07:13:10
把json格式对象转成可提交字符串格式,会过滤掉函数 {a: {b: 3}, b: [1], c: "d"} -> a.b=3&b[0]=1&c=d
var json = {
name: "任务名称" ,
scoreRule: "",
score: "", // 如果规则表达式不为空,则默认选中 “按规则表达式计算”
unique: 1,
startTime: "2014-09-15 20:20:20",
endTime: "2014-10-15 20:20:20",
status: 1,
isTaks: 0,
tradeType: 1,
description: "业务描述" ,
codes: [ "16", "6" ], // 选中的平台
ids: [ "3"], // app内部链接
test: {
a: 1,
b: [1, 2, 3]
}
}; var json2 = {
a: 1,
b: 2,
c: {
a: 1,
b: {
a: 1,
b: [1, 2]
},
c: [1, 2]
},
d: [1, 2, {
a: 1,
b: {
a: 1
},
c: [1, 2]
}]
}; /**
* 把json格式对象转成可提交字符串格式,会过滤掉函数 {a: {b: 3}, b: [1], c: "d"} -> a.b=3&b[0]=1&c=d
* @param {Object} data 要转化的json对象
* @param {String} prefix 要带的前缀
* @return {String} 字符串
*/
function paramData(data, prefix) {
var _getType = ({}).toString,
_paramArray = function(arr, prefix) {
var result = [],
j = 0,
len = arr.length; for (; j < len; j++) {
var data = arr[j],
type = _getType.call(data),
subPrefix = prefix + "[" + j + "]"; result = result.concat(_paramAll(arr[j], prefix + "[" + j + "]"));
} return result;
},
_paramAll = function(data, prefix) {
var result = [],
type = _getType.call(data); switch (type) {
case "[object Object]" :
var subPrefix = prefix ? prefix + "." : "",
i; for (i in data) result = result.concat(_paramAll(data[i], subPrefix + i));
break;
case "[object Array]" :
result = result.concat(_paramArray(data, prefix));
break;
case "[object String]" :
case "[object Number]" :
result.push(prefix + "=" + data);
} return result;
}; prefix = prefix || "";
// if (prefix) { // prefix必须以 . 结尾
// prefix = /\.$/.test(prefix) ? prefix : (prefix + ".");
// } else {
// prefix = "";
// } return (function () {
return _paramAll(data, prefix);
}()).join( "&");
} console.log(paramData(json2, "rule"));
console.log(paramData(json, "rule"));